4

I want to load custom html in a webview using react native, it's working for simple html but I can't figure out how to load javascript from a js file to the webview, it looks like nothing happen.

Here is my webview :

 var html = '<!DOCTYPE html><html><head><script src="myfile.js" type="text/javascript"></script></head><body><h1>This is a heading!</h1><div id="here"></div></body></html>';

    return (
      <WebView html={html}
               javaScriptEnabled={true} />
    );

And here I have my simple js file (myfile.js):

document.addEventListener("DOMContentLoaded", function(event) {
   alert("HERE");
   var generateHere = document.getElementById("here");
generateHere.innerHTML = '<div class="someclass"><a href="www.example.com"><p>some text</p></a></div>';
});

I tried it in my web browsers it works.

3
  • Edit : I already find this link stackoverflow.com/questions/33818641/… Commented Jan 6, 2016 at 22:52
  • 2
    Where did you place your myfile.js? Commented Jan 6, 2016 at 23:34
  • in the Xcode project Commented Jan 7, 2016 at 9:08

2 Answers 2

2

You need to use the injectedJavaScript attribute on the WebView to pass over JS to be executed.

For example:

<WebView html={html}
    injectedJavaScript={'function myfunc() { //your JS here };myfunc();'}
    javaScriptEnabled={true} /> 
Sign up to request clarification or add additional context in comments.

3 Comments

How is it possible to load css into the webview with this method?
Is this possible?
Maybe you could inject css via JavaScript?
1

scgough's code injects JS; here is how you can also inject CSS with JavaScript:

<WebView html={html}
    injectedJavaScript={`let customCSS = "body { font-weight: 'bold'; font-size: '17px'; }"//your CSS
    let headTag = document.getElementsByTagName('head')[0];
    let styleTag = document.createElement('style')
    headTag.appendChild(styleTag);
    styleTag.type = 'text/css';
    styleTag.appendChild(document.createTextNode(customCSS));`}
    javaScriptEnabled={true} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.