gpt4 book ai didi

react-native - 使用 injectJavaScript 在 WebView 中调用函数

转载 作者:行者123 更新时间:2023-12-04 01:58:33 25 4
gpt4 key购买 nike

我一直在寻找 injectJavaScript 的例子。在 GitHub 上,我发现了一些,我想是为了测试,做:

injectJavaScript={()=>'alert("Injected JS ")'}

但我无法让它工作。我想也许我必须等待 WebView 加载,但仍然没有运气。

这是我的测试:

export default class App extends React.Component {
constructor( props ){
super( props );

this.state = {
loaded: false
};
}
webviewDidLoad(){
this.setState({loaded: true});
}
render() {
return (
<WebView
source={ webview }
injectJavaScript={ this.state.loaded ? ()=>'alert("Injected JS")' : null }
onLoadEnd={ this.webviewDidLoad.bind(this) }
/>
);
}
}

是通过字符串和 props 与 WebView 通信的唯一方法吗?无法与传递 native javascript 对象的 WebView 方法通信?

感谢您的帮助!

最佳答案

import React, { Component } from 'react';
import {
Text,
View,
StyleSheet,
TouchableHighlight,
WebView,
} from 'react-native';

let jsCode = `
document.querySelector('#myContent').style.backgroundColor = 'blue';
`;

export default class App extends Component {
render() {
return (
<View style={localStyles.viroContainer}>

<WebView
source={{ html: "<h1 id='myContent'>Hello</h1>" }}
style={{ flex: 1 }}
ref={webview => {this.myWebview = webview;}}
injectedJavaScript={jsCode}
javaScriptEnabled={true}
/>

<TouchableHighlight
style={localStyles.overlayButton}
onPress={this.sendMessageToWebView2}
underlayColor="transparent">
<Text>Send message to WebView</Text>
</TouchableHighlight>

</View>
);
}

sendMessageToWebView2 = () => {
console.log(this.myWebview);
console.log(this);
this.myWebview.injectJavaScript(`
(function () {
document.querySelector('body').style.backgroundColor = 'orange';
})();
`);
};
}

var localStyles = StyleSheet.create({
viroContainer: {
flex: 1,
},
overlayButton: {
position: 'absolute',
bottom: 0,
left: 110,
height: 50,
width: 150,
paddingTop: 30,
paddingBottom: 30,
marginTop: 10,
marginBottom: 10,
backgroundColor: '#f0a0aa',
borderRadius: 10,
borderWidth: 2,
borderColor: '#000',
},
});

关于react-native - 使用 injectJavaScript 在 WebView 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48954489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com