[英]Injecting Javascript in android Webview
我要在我的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
時,它將用戶重定向到WebView中的另一個頁面,例如,當用戶轉到此頁面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());
}
您可以使用WebView.loadUrl(String javascriptCodeUrl) 。 確保指定注入的URL為javascript。 即以javascript:
作為字符串的前綴。
Webview webView = (WebView)findViewById(R.id.myWebView);
webView.loadUrl("http://examplex.com/index.php?access_token=ASDFG");
String javascriptCodeUrl= "javascript:var token = "+
"top.location.href.split('access_token=')[1]; "+
"if (token) { "+
"top.location.href = 'http://example.com/index.php?token=' + token;}";
webView.loadUrl(javascriptCodeUrl);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.