简体   繁体   English

根据WebView React Native中正在查看的当前页面注入不同的Javascript

[英]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. 我构建了一个IOS应用程序,该应用程序使用WebView加载网站并通过单击带有Javascript的按钮浏览用户,浏览4页。 I am converting this application to React Native now and when the second page loads the Javascript does not seem to fire off. 我现在正在将该应用程序转换为React Native,并且在第二页加载时,似乎没有触发Javascript。 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. 我以为这是因为丢失了,但是我不确定React Native是否继续在每次加载页面时或仅在加载的第一页上注入javascript,而在客户端重新加载或更改后可能会丢失该页面。

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? 请告诉我将特定的Javascript注入WebView的正确方法,具体取决于WebView当前正在查看哪个页面?

In my example above I am showing 2 steps. 在上面的示例中,我显示了2个步骤。 Step 1 is successful but when the WebView loads the second page the second step of Javascript is not successful. 步骤1成功,但是当WebView加载第二页时,Javascript的第二步不成功。

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. 这样,只要您的页面重新加载,它就会执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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