Princé Housein
Princé Housein

Reputation: 41

Injecting Javascript in android Webview

I have the following JavaScript lines i want to execute it in my WebView.

var token = top.location.href.split('access_token=')[1];
if (token) {
top.location.href = "http://example.com/index.php?token=" + token;
}

When the WebView have access_token in the link it redirect the user to another page in WebView etc when the user go to this page http://examplex.com/index.php?access_token=ASDFG the app redirect him to http://example.com/index.php?token=ASDFG

Full code after execute it:

   @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());
        }

Upvotes: 0

Views: 1243

Answers (1)

ben75
ben75

Reputation: 28706

You can use the WebView.loadUrl(String javascriptCodeUrl). Be sure to specify that the injected url is javascript. i.e. prefix the string with 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);

Upvotes: 2

Related Questions