javascript - 你如何在 React-Native WebView 中执行 Javascript?
问题描述
我正在尝试在 iOS 建议上加载的 WebView 中执行 javascript。我试图让一个非常简单的示例工作,但它始终抛出未定义或 TypeError。
这是代码:
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>
);
}
}
请不要推荐使用注入Javascript,因为那不是我想要的功能。
也将不胜感激任何其他方法。
解决方案
根据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>
);
}
}
希望这对您有所帮助。随意怀疑。
推荐阅读
- javascript - 我如何知道 Rhino 中的异步 JavaScript 执行何时完成
- python - Matplotlib:在同一轴位置显示次要刻度和主要刻度
- angular - 用于@angular/compiler@~8.2.4 的 npm WARN tarball tarball 数据
- docker - 使用 Docker 安装 Nifi - 无法访问网络服务器
- c - 尝试运行老虎机程序时随机出现错误代码
- angular - CSS编辑angular2 datepicker不起作用
- reactjs - 在 React Router 中将“activeClassName”添加到 NavLink
- javascript - 反应计数器增加直到输入值
- python - ibm_db_dbi::ProgrammingError:光标无法关闭;连接不再活跃
- javascript - 在 MySQL 中检索数据类型为 DATETIME 的列数据会将数据转换为 ISO 格式