基于在WebView中查看的当前页面注入不同的Javascript
背景 我构建了一个IOS应用程序,它使用WebView加载一个网站,并通过Javascript单击按钮在4个页面中导航用户。我现在正在将这个应用程序转换为React Native,当第二个页面加载时,Javascript似乎不会启动。我假设这是因为它丢失了,但我不确定React-Native是否会继续在每个页面加载上注入javascript,或者只在客户端重新加载或更改后可能丢失的第一个页面上注入javascript 示例基于在WebView中查看的当前页面注入不同的Javascript,javascript,react-native,Javascript,React Native,背景 我构建了一个IOS应用程序,它使用WebView加载一个网站,并通过Javascript单击按钮在4个页面中导航用户。我现在正在将这个应用程序转换为React Native,当第二个页面加载时,Javascript似乎不会启动。我假设这是因为它丢失了,但我不确定React-Native是否会继续在每个页面加载上注入javascript,或者只在客户端重新加载或更改后可能丢失的第一个页面上注入javascript 示例 const injectedJavaScript: = ` le
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}
/>
const injectedJavaScript:=`
让currentStep=“login”;
如果(currentStep==“登录”){
document.getElementById('userID')。value='0${
this.props.username
}';document.getElementById('userPassword')。value='0${
这个密码是.props.password
}';document.getElementById('login')。单击();
currentStep='agreeToTerms';
}else if(currentStep=='agreeToTerms'&&window.location.href=='https://www.example.com") {
currentStep='下载';
document.getElementsByClassName('button')[0]。单击();
}
`;
this.webviewererror(e)}
startInLoadingState={true}
scalesPageToFit={true}
/>
问题
请告诉我将特定Javascript注入WebView的正确方法,具体取决于当前在WebView中查看的页面
在上面的例子中,我展示了两个步骤。步骤1成功,但当WebView加载第二个页面时,Javascript的第二个步骤不成功 将注入脚本更改为
<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}
/>
this.webview错误(e)}
startInLoadingState={true}
scalesPageToFit={true}
onLoad={this.updateInjectedJavaScript}
/>
以便在页面重新加载时执行 这仍然存在同样的问题。我敢肯定,一旦第二个页面呈现出来,注入的JS就消失了。你确定它还应该在那儿吗?谢谢你的帮助,但我知道了。如果您只是简单地使用,
onLoad={this.updateInjectedJavaScript}
每次加载新页面时,该函数都会启动,我可以通过跟踪已将用户定向到的页面,将新的JS注入到WebView中this.webview.injectJavaScript(injectedJavaScript)如果你想为其他人更新你的解决方案,我很乐意接受。再次感谢!