我想要在我的WebView中执行以下JavaScript行。
var token = top.location.href.split('access_token=')[1];
if (token) {
top.location.href = "http://example.com/index.php?token=" + token;
}
当WebView在链接中有access_token
时,当用户转到此页http://examplex.com/index.php?access_token=ASDFG时,该应用会将用户重定向到另一个页面http://example.com/index.php?token=ASDFG
执行后的完整代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
String javascriptCodeUrl= "javascript:var token = \n"+
"top.location.href.split('access_token=')[1]; \n"+
"if (token) { \n"+
"top.location.href = 'http://example.com/index.php?token=' + token;}";
mWebView.loadUrl(javascriptCodeUrl);
mWebView.loadUrl("http://default-webpage.com");
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
}