【问题标题】:Include external JavaScript file in the WebView of React Native App在 React Native App 的 WebView 中包含外部 JavaScript 文件
【发布时间】:2017-04-07 08:22:32
【问题描述】:

我正在尝试在我的 React Native 项目的 WebView 中包含一个外部 JavaScript 文件。我希望包含的文件是在npm 上不可用的第三方库,用纯 JavaScript(没有 ES5 或更高版本)编写。我需要一个解决方案,将我的 JS 文件注入到 React Native 项目的 WebView 中,而无需导入它或使其成为 npm 模块。

我尝试了以下方法,但目前没有任何效果:

这是我的外部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='&nbsp;';"></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>
    );
  }

}

【问题讨论】:

  • 为什么要使用webview来执行代码?
  • @MartinCup 我的 JS 文件是一个 JS 电子表格引擎。将整个库转换为模块,然后在导入语句中使用它不是最佳解决方案。因此,我想包含这个文件,因为它是在基于 cordova 的应用程序中完成的,即在 web 视图中。请提出最佳方法。

标签: javascript react-native


【解决方案1】:

也许您可以尝试将您的 JS 文件捆绑为资产,然后像在“本机”WebView 中那样引用该文件。看看Android 的这个答案和 iOS 的这个答案,[1] 和 [2]。

【讨论】:

  • 我也认为这是解决方案
【解决方案2】:

在 RN WebView 中加载 JavaScript 的唯一方法是使用 injectedJavaScript 属性,这只能采用纯字符串(而不是文件路径)。就我而言,我是这样做的:

首先生成一个文件,其中包含您转换为纯字符串的 JS 文件:

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 中导入的位置。

然后只需导入文件并将其注入 WebView:

const myJsLib = require('external-lib.js');
const webView = <WebView injectedJavaScript={myJsLib} .....

这不是一个特别漂亮的解决方案,但效果很好。

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 2017-10-25
    • 2020-03-19
    • 2017-09-10
    • 2011-06-15
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多