如何使用 React Native 监控 webview 文档标题的变化

尼克森85

我基本上尝试在 webview 中的文档标题更改时立即调用 react native 中的函数。我已经使用以下代码获得了在我的 webview 中显示的网页的 document.title:

  handleMessage(message) {
    alert(message.nativeEvent.data);
  }

  render() {
    return (
      <WebView
        source={{ uri: "https://website.com/" }}
        injectedJavaScript="window.postMessage(document.title)"
        onMessage={this.handleMessage}
      />
    )
  }

现在我想监视标题的更改并在发生这种情况时立即调用函数。我怎样才能做到这一点?

穆图克里希南

我来到这里寻找相同问题的解决方案,但在 stackoverflow 上找不到。我的确切要求是从 WebView 读取标题并在其他地方的文本框中更新它,这就是我解决它的方法,

我注入的 javascript 监控 WebView 中 URL 的变化,并在发生变化时调用postMessage

这是我注入的脚本:

window.currentloc = location.href;
setInterval(function() {
    if (window.currentloc != location.href) {
        window.currentloc = location.href;
        window.postMessage('$#doctitle-' + document.title);
    }
}, 500);

我还为我的消息添加了前缀,$#doctitle-以避免处理来自我的 WebView 的所有消息。

我的组件如下所示:

<WebView
     ref={r => (this.webview = r)}
     style={{ flex: 1 }}
     injectedJavaScript="window.currentloc = location.href;setInterval(function() {if (window.currentloc != location.href) {window.currentloc = location.href;window.postMessage('$#doctitle-' + document.title);}}, 500);"
     javaScriptEnabled={true}
     onMessage={this.handleMessage.bind(this)}
     onNavigationStateChange={this.onNavigationStateChange.bind(this)}
     source={{
     uri: 'https://website.com',
   }}
/>

我的消息处理程序代码:

handleMessage(event) {
        if(event.nativeEvent.data && event.nativeEvent.data.indexOf("$#doctitle-")==0){
          this.setState({
            windowTitle: event.nativeEvent.data.split('-')[1]
          });
        }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章