【问题标题】:Injecting Javascript in android Webview在android Webview中注入Javascript
【发布时间】:2015-11-07 14:43:26
【问题描述】:

我想在我的 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());
        }

【问题讨论】:

    标签: javascript java android android-studio android-webview


    【解决方案1】:

    您可以使用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);
    

    【讨论】:

    • 我可以在 webView.loadUrl(javascriptCodeUrl) 之后添加吗?像这样的默认 Webview:webView.loadUrl(exampleee.com);并且 javascript 代码将继续工作?
    • @PrincéHousein 查看我的编辑。 (先加载页面,再加载javascript)
    • 在我将问题编辑为完整脚本的同一个默认网页中仍然无法正常工作
    • 先加载页面,再加载js代码url。查看我的代码和我的第一条评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多