manuelBetancurt
manuelBetancurt

Reputation: 16138

react native react-native-web-view working ok with embedded JS but not with separate JS

I have a test app with react-native-web-view rendering a local HTML file

for using JS, it works if I have the JS embedded in the HTML, but if I call it on a separate JS file it won't work...

in my App.tsx:

  <WebView source={{uri: `${origin}/${file}`}} style={styles.webview} />

here is the embedded HTML:

<button type="button" onclick="alabama();">Play</button>
<button type="button" onclick="alert('Hello alabama')">music</button>
<script src="./chusa.js"></script>

chusa.js:

function alabama() {
  alert('Hello alabama');
}

So, alert works, the function doesn't.

How can I call the script on a separate file?

Upvotes: 0

Views: 768

Answers (1)

DarkComet
DarkComet

Reputation: 41

React-Native Web WebView uses an iframe in replace of the webview component, so the issue is likely due the html file (e.g. the iframe) not having access to external files once mounted/created.

Possible Solution:

  1. If you want the file to still be external, change it to a string and use back-quotes: export const javascript = `alert("hello")`
  2. Import js component. Something like: import externalJS from "./filename"
  3. The imported variable is a string and your html should also be a string, so you'll want to append the script string to the end of the html string. Something like this: html = html.replace('</body>', '<script>${externalJS}</script></body>')
  4. Use the new html string as the source via prop: <WebView source={{ html: html }/>

Note: When you say "call" the script, if you are referring to calling a function after the web webview has been created without re-rendering, then that isn't possible at this time due when using the web webview instead of an actual webview component. This is actually an issue I am trying to resolve: How do I post a message to a iframe (not webview) in React-Native?

Hopefully this helps you with your issue.

Upvotes: 1

Related Questions