我有一个Webview,在此Webview中,我必须注入js代码以获取信息,然后通过onMessage检索此信息。
问题在于onMessage永远不会被激活,它不会收到任何信息。
我在postMessage和onMessage之间遇到问题,看来他们无法交流。
我正在尝试在android上
链接:Expo
代码:
import React, { Component } from 'react';
import { View, WebView } from 'react-native';
export default class ResolveUrl extends Component {
constructor() {
super();
this.state = {
urlOpenload: '',
code: '',
isMounted: false,
};
}
componentDidMount() {
this.setState({ isMounted: true });
}
componentWillUnmount() {
this.setState({ isMounted: false });
}
Openload(url) {
return new Promise(async (resolve, reject) => {
setTimeout(() => {
if (this.state.isMounted) {
this.setState({ urlOpenload: url });
setInterval(() => {
if (this.state.code != '')
resolve('https://openload.co/stream' + this.state.code);
}, 5000);
}
}, 1000);
});
}
get(type, url) {
type = type.toLowerCase();
return new Promise(async (resolve, reject) => {
switch (type) {
case 'openload':
resolve(this.Openload(url));
break;
}
});
}
render() {
const jsCodeOpenload = `
(function ready() {
function whenRNPostMessageReady(cb) {
if (window.postMessage.length === 1) cb();
else setTimeout(function() { whenRNPostMessageReady(cb) }, 100);
}
whenRNPostMessageReady(function() {
window.postMessage(document.getElementById('lqEH1').innerHTML);
});
})();`;
return (
<View>
{this.state.urlOpenload != '' && (
<WebView
source={{
uri: this.state.urlOpenload,
}}
onMessage={evt => {
alert(evt.nativeEvent.data)
this.setState({ code: evt.nativeEvent.data });
}}
injectedJavaScript={jsCodeOpenload}
javaScriptEnabled
style={{ flex: 1 }}
/>
)}
</View>
);
}
}