Reputation: 16138
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
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:
export const javascript = `alert("hello")`
import externalJS from "./filename"
html = html.replace('</body>', '<script>${externalJS}</script></body>')
<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