0

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

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

can i add after webView.loadUrl(javascriptCodeUrl); Default Webview like this : webView.loadUrl(exampleee.com); and the javascript code will remain working ?
@PrincéHousein see my edit. (first load the page, then load the javascript)
not working it still in the same default webpage i edited my question to the full script
load the page first, then the js code url. see my code and my first comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.