最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Include external JavaScript file in the WebView of React Native App - Stack Overflow

programmeradmin0浏览0评论

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:

  • 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

This is my external AppGeneral.js:

function AppGeneral(){
     alert("Ok");
}
var app = new AppGeneral();

This is my index.ios.js file:

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>
    );
  }

}

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:

  • 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

This is my external AppGeneral.js:

function AppGeneral(){
     alert("Ok");
}
var app = new AppGeneral();

This is my index.ios.js file:

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>
    );
  }

}
Share Improve this question edited May 23, 2017 at 10:31 CommunityBot 11 silver badge asked Nov 23, 2016 at 10:57 Manu GuptaManu Gupta 3511 gold badge5 silver badges18 bronze badges 3
  • Why do you want to use the webview to execute code? – Martin Cup Commented Nov 24, 2016 at 1:32
  • @MartinCup My JS file is a JS Spreadsheet engine. Converting the entire library into a module and then using it in the import statement would not be the optimal solution. Therefore, I wanted to include this file as it is done in a cordova based app i.e in the webview. Kindly suggest the best approach. – Manu Gupta Commented Nov 25, 2016 at 7:32
  • @Manu Gupta - did you find a way to solve the problem? – Abolfazl Roshanzamir Commented Jun 7, 2022 at 9:50
Add a comment  | 

3 Answers 3

Reset to default 8

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:

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);

And make sure "/my-rn-app/external-lib.js" is somewhere where it can be imported in React Native.

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.

Maybe you can try bundling your JS file as an asset and then refer to the file as you would in a 'native' WebView. Have a look at this answer for Android and this ones for iOS, [1] and [2].

I ended up pasting the js source code around <script> my js code ... <script/> tags

发布评论

评论列表(0)

  1. 暂无评论