简体   繁体   中英

Injecting different Javascript based on the current page being viewed in WebView React Native

Background

I built an IOS application that uses WebView to load a website and navigate a user through 4 pages by clicking the buttons with Javascript. I am converting this application to React Native now and when the second page loads the Javascript does not seem to fire off. I am assuming this is because it is lost but I am not sure if React Native continues to inject the javascript on each page load or only on the first page that loads which could be lost after the client reloads or changes.

Example

const injectedJavaScript: = `
    let currentStep = "login";
    if(currentStep === 'login') {
      document.getElementById('userID').value =  '${
        this.props.username
      }'; document.getElementById('userPassword').value = '${
        this.props.password
      }'; document.getElementById('login').click();
      currentStep = 'agreeToTerms';
    } else if(currentStep === 'agreeToTerms' && window.location.href === "https://www.example.com") {
      currentStep = 'download';
      document.getElementsByClassName('button')[0].click();
    }
    `;


  <WebView
        ignoreSslError={true}
        source={{ uri: "https://www.example.com" }}
        style={{ marginTop: 20, height: 400, width: 400 }}
        injectedJavaScript={injectedJavaScript}
        javaScriptEnabledAndroid={true}
        onError={() => this.webviewError(e)}
        startInLoadingState={true}
        scalesPageToFit={true}
      />

Question

Please tell me the correct way to inject specific Javascript to the WebView depending on which page is currently being viewed in the WebView?

In my example above I am showing 2 steps. Step 1 is successful but when the WebView loads the second page the second step of Javascript is not successful.

change your inject script to

 <WebView
    ignoreSslError={true}
    source={{ uri: "https://www.example.com" }}
    style={{ marginTop: 20, height: 400, width: 400 }}
    injectedJavaScript={injectedJavaScript}
    javaScriptEnabledAndroid={true}
    onError={() => this.webviewError(e)}
    startInLoadingState={true}
    scalesPageToFit={true}
    onLoad={this.updateInjectedJavaScript}
  />

so that it will be executed when ever your page is reloaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM