Search code examples
javascriptreact-nativeonchange

How to monitor changes in webview document title with react native


I basically try to call a function in react native as soon as the document title in my webview changes. I already get the document.title of the web page that is shown in my webview by using this code:

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

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

Now I want to monitor the title for changes and call a function as soon as this happens. How can I do this?


Solution

  • I came here looking for a solution to the same problem but couldn't find one on stackoverflow. My exact requirement was to read the title from WebView and update it on a text box somewhere else and this is how I solved it,

    My injected javascript monitors changes in the URL within WebView and calls postMessage whenever there is a change.

    Here is my injected script:

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

    I also prefixed my message with $#doctitle- to avoid processing all messages coming from my WebView.

    My component looks like this:

    <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',
       }}
    />
    

    My message handler code:

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