React Native Webview给本地SPA的URI添加参数失败如何解决?
报错根因
报错的核心原因是移动端本地文件资源是按真实文件名匹配的,你在index.html后拼接查询参数、路径后缀后,系统会将完整字符串当作目标文件名查找,自然找不到不存在的index.html?parameter=foo文件,因此报URI不存在错误。
推荐解决方案(按优先级排序)
方案1:使用injectedJavaScript注入初始化参数(最推荐)
直接在WebView加载页面时,将参数预先注入到页面全局环境,SPA加载后直接读取即可,不需要修改原有资源路径。
// 定义需要传递的初始化参数 const initParams = { parameter: 'foo', // 可扩展其他参数 }; // 拼接注入脚本,将参数挂载到页面window对象 const injectedJS = ` window.REACT_NATIVE_INIT_PARAMS = ${JSON.stringify(initParams)}; true; // 必须添加该行返回值,避免部分WebView版本执行注入时报错 `; // 资源路径保持原有正常写法即可 const source = (Platform.OS === 'android' ? 'file:///android_asset/' : '') + 'SPA/index.html';
修改WebView配置,添加注入脚本属性:
<WebView originWhitelist={["file://"]} useWebKit={true} onMessage={this.invoke.listener} source={{ uri: source }} injectedJavaScript={injectedJS} // 新增注入脚本配置 style={{ marginTop: 20, flex: 1, backgroundColor: 'transparent' }} bounces={false} scrollEnabled={false} overScrollMode={'never'} />
SPA页面内直接读取全局参数做初始化:
// SPA初始化逻辑中添加 const initParams = window.REACT_NATIVE_INIT_PARAMS || {}; const targetParam = initParams.parameter; // 即可拿到传递的foo值
方案2:页面加载完成后通过postMessage传递参数
如果参数是异步获取的,或者需要在页面加载完成后动态传递,可使用该方案:
<WebView originWhitelist={["file://"]} useWebKit={true} onMessage={this.invoke.listener} source={{ uri: source }} ref={ref => this.webviewRef = ref} // 绑定WebView实例引用 onLoadEnd={() => { // 页面加载完成后发送参数 const params = { parameter: 'foo' }; this.webviewRef.postMessage(JSON.stringify(params)); }} style={{ marginTop: 20, flex: 1, backgroundColor: 'transparent' }} bounces={false} scrollEnabled={false} overScrollMode={'never'} />
SPA页面内监听消息事件获取参数:
window.addEventListener('message', (event) => { const params = JSON.parse(event.data); const targetParam = params.parameter; // 拿到参数后执行初始化逻辑 });
方案3:伪造location查询参数(仅适合SPA已写死从url取参的场景)
如果你的SPA已经固定从location.search读取参数,不想修改前端代码,可通过伪造location属性的方式实现:
// 配置资源根路径 const baseUrl = Platform.OS === 'android' ? 'file:///android_asset/SPA/' : './SPA/'; // 构造HTML内容,提前注入伪造的location.search const htmlContent = ` <!DOCTYPE html> <html> <head> <base href="${baseUrl}" /> <script> Object.defineProperty(window.location, 'search', { value: '?parameter=foo', writable: false }); </script> </head> <body> <script src="index.html"></script> </body> </html> `;
修改WebView的source属性为HTML内容:
<WebView originWhitelist={["file://"]} useWebKit={true} onMessage={this.invoke.listener} source={{ html: htmlContent, baseUrl: baseUrl }} // 替换原有uri配置 style={{ marginTop: 20, flex: 1, backgroundColor: 'transparent' }} bounces={false} scrollEnabled={false} overScrollMode={'never'} />
内容的提问来源于stack exchange,提问作者alcolopa
相关产品推荐
相关产品推荐

