首页 > 解决方案 > 根据在 WebView 中查看的当前页面注入不同的 JavaScript

问题描述

请告诉我根据当前在 WebView 中查看的页面,将特定 JavaScript 注入 WebView 的正确方法?

我想展示 2 个步骤。第 1 步成功,但是当 WebView 加载第二个页面时,JavaScript 的第二步不成功。

     const injectedJavaScript: = `
    let currentStep = "step1";
    if(currentStep === 'step1') {
      document.getElementById('username').value =  '${
        this.props.username
      }'; document.getElementById('password').value = '${
        this.props.password
      }'; document.getElementById('login').click();
      currentStep = 'step2';
    } else if(currentStep === 'step2' && 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}
      />

标签: javascriptreact-nativewebview

解决方案


推荐阅读