[英]How do you execute Javascript in React-Native WebView?
我正在尝试在加载到 iOS 建议上的 WebView 中执行 javascript。 我试图让一个痛苦的简单示例工作,但它始终抛出未定义或类型错误。
这是代码:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { WebView } from 'react-native-webview';
export default class App extends Component {
constructor(props){
super(props)
this.onPressButton = this.onPressButton.bind(this)
}
onPressButton(){
this.webview.injectJavascript(`alert('hello')`)
}
render() {
return (
<View style={{ height: '100%' }}>
<WebView
ref={ref => (this.webview = ref)}
javaScriptEnabled={true}
source={{ uri: 'https://google.com' }}
/>
<Button onPress={this.onPressButton} style={{ height: '10%' }} title="Test Javascript" />
</View>
);
}
}
请不要推荐使用injectedJavascript,因为这不是我想要的功能。
也将不胜感激任何其他方法。
根据react-native-webview ,您需要使用injectJavaScript
,而不是injectJavascript
。 那会解决你的问题。
此外,还有一些事情需要改变
this.onPressButton = this.onPressButton.bind(this)
而您可以使用箭头函数。javaScriptEnabled={true}
。 它已经使用默认值作为true
。true
。 这是必需的,否则您有时会遇到无声的失败。检查完整的示例代码
import React, { Component } from "react";
import { View, Button } from "react-native";
import { WebView } from "react-native-webview";
const script = `
alert('hello')
true;
`;
export default class App extends Component {
onPressButton = () => {
this.webview.injectJavaScript(script);
};
render() {
return (
<View style={{ flex: 1 }}>
<WebView
ref={ref => (this.webview = ref)}
source={{ uri: "https://google.com" }}
/>
<Button onPress={this.onPressButton} title="Test Javascript" />
</View>
);
}
}
希望这对你有帮助。 如有疑问,请放心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.