React Native WebView无法加载Script标签问题求助
React Native WebView加载API返回的Script标签空白问题解决方法
问题重现
你尝试在React Native WebView中加载从API获取的script标签,代码如下:
获取的脚本代码:
const html3 = `<script type="text/javascript" src="https://g.adspeed.net/ad.php?do=js&zid=91679&oid=14755&wd=-1&ht=-1&target=_blank"></script>`
WebView代码:
return ( <> <WebView source={{html3}} originWhitelist={['*']} style={{marginTop: 220, height: 150}} /> </> );
运行后WebView显示空白,以下是具体解决步骤:
解决步骤
1. 修正source属性格式
WebView的source对象需要明确指定html字段,你当前的{{html3}}写法错误,应改为{ html: html3 },让WebView正确识别要加载的HTML内容。
2. 包裹完整HTML文档结构
单独的script标签无法被WebView正确解析执行,需要将脚本嵌入完整的HTML文档结构中,同时添加视口设置确保内容适配:
const html3 = ` <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <script type="text/javascript" src="https://g.adspeed.net/ad.php?do=js&zid=91679&oid=14755&wd=-1&ht=-1&target=_blank"></script> </body> </html> `
3. 显式启用JavaScript
尽管多数环境下WebView默认开启JavaScript,但显式设置javaScriptEnabled={true}可避免环境差异导致的脚本无法执行问题。
4. 可选:添加加载监听用于调试
若仍显示空白,可通过onLoad和onError回调排查加载状态,确认脚本是否成功执行:
修改后的完整代码
import React from 'react'; import { WebView } from 'react-native-webview'; const AdWebView = () => { const html3 = ` <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <script type="text/javascript" src="https://g.adspeed.net/ad.php?do=js&zid=91679&oid=14755&wd=-1&ht=-1&target=_blank"></script> </body> </html> `; return ( <WebView source={{ html: html3 }} originWhitelist={['*']} javaScriptEnabled={true} style={{ marginTop: 220, height: 150 }} onLoad={() => console.log('WebView加载完成')} onError={(error) => console.log('加载错误:', error)} /> ); }; export default AdWebView;
额外说明
- 脚本中的
wd=-1和ht=-1表示自适应宽高,确保WebView设置的150px高度足够容纳广告内容。 originWhitelist={['*']}已允许所有源,无需额外处理跨域问题。
内容的提问来源于stack exchange,提问作者Harshal Kalavadiya
相关产品推荐
相关产品推荐

