在 React Native App 的 WebView 中包含外部 JavaScript 文件 [英] Include external JavaScript file in the WebView of React Native App
问题描述
我正在尝试在 React Native 项目的 WebView 中包含一个外部 JavaScript 文件.我希望包含的文件是用纯 JavaScript(无 ES5 或更高版本)编写的 npm
上不可用的第三方库.我需要一个解决方案,将我的 JS 文件注入 React Native 项目的 WebView 中,而无需导入它或将其设为 npm 模块.
I'm trying to include an external JavaScript file inside a WebView of my React Native project. The file I wish to include is a third party library not available on npm
written in plain JavaScript (No ES5 or higher). I need a solution for injecting my JS file in the WebView of the React Native project without importing it or making it an npm module.
我尝试了以下方法,但目前没有任何效果:
I have tried the following methods but nothing works as for now:
- 我尝试像这样加载脚本:插入脚本标签
- 我尝试在
injectedJavaScript
中动态加载脚本,参考以下答案:从 JS 文件链接 JS 文件
- I have tried to load the script like this: Insert script tag
- I have tried to load the script dynamically in
injectedJavaScript
following the answer here: Link JS file from a JS file
这是我的外部 AppGeneral.js
:
function AppGeneral(){
alert("Ok");
}
var app = new AppGeneral();
这是我的 index.ios.js
文件:
export default class sampleReactApp extends Component {
render() {
let HTML = `
<html>
<head>
<script type="text/javascript" src="js/AppGeneral.js"></script>
</head>
<body>
<div id="workbookControl"></div>
<div id="tableeditor">editor goes here</div>
<div id="msg" onclick="this.innerHTML=' ';"></div>
</body>
</html>
`;
let jsCode = `
alert("Js");
`;
return (
<View style={styles.container}>
<WebView
style={styles.webView}
ref="myWebView"
source={{ html: HTML }}
injectedJavaScript={jsCode}
javaScriptEnabledAndroid={true}
>
</WebView>
</View>
);
}
}
推荐答案
在 RN WebView 中加载 JavaScript 的唯一方法是使用 injectedJavaScript
属性,并且这只能采用纯字符串(不是文件路径).就我而言,我是这样做的:
The only way to load JavaScript in a RN WebView is using the injectedJavaScript
property, and this can only take a plain string (not a file path). In my case, I've done it this way:
首先生成一个文件,其中包含您转换为纯字符串的 JS 文件:
First generate a file that contains your JS file converted to a plain string:
const fs = require('fs-extra');
const filePath = '/path/to/your/lib.js';
const js = await fs.readFile(filePath, 'utf-8');
const json = 'module.exports = ' + JSON.stringify(js) + ';';
await fs.writeFile('/my-rn-app/external-lib.js', json);
并确保/my-rn-app/external-lib.js"位于可以在 React Native 中导入的地方.
And make sure "/my-rn-app/external-lib.js" is somewhere where it can be imported in React Native.
然后只需导入文件并将其注入到 WebView 中:
Then simply import the file and inject it in the WebView:
const myJsLib = require('external-lib.js');
const webView = <WebView injectedJavaScript={myJsLib} .....
这不是一个特别漂亮的解决方案,但效果很好.
This is not a particularly pretty solution but it works well.
这篇关于在 React Native App 的 WebView 中包含外部 JavaScript 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!