0

I have a Javascript code for Mozilla Firefox which insert a link in different websites when they have a special condition. I was thinking to do an app to do the same in my Android mobile phone. I have done an app which loads an URL and I can see this website in a webView. Now, I would like to insert my JavaScript code with the intention of do the same but I do not how to do it.

    public void onCreate(Bundle InstanceState)
     {
    super.onCreate(InstanceState);
    setContentView(R.layout.main);

    webBrowser = (WebView) findViewById(R.id.webkit);
    webBrowser.getSettings().setJavaScriptEnabled(true);
    webBrowser.loadUrl("http://www.onekin.org");
         }

I have seen that I should use this function but it has been impossible to let it work

addJavascriptInterface(Object object, String name)

Does somebody know how I can do it? Thanks

2 Answers 2

1

You can try using your own WebViewClient:

Define your link

private String link = "http://yourlink.html";

Adapt your code to something like:

webBrowser.getSettings().setJavaScriptEnabled(true);
webBrowser.setWebViewClient(new TestWebViewClient());
webBrowser.loadUrl("http://www.onekin.org");
// Interface to inject your javascript
webBrowser.addJavascriptInterface(new JavaScriptInterface(), "MYJSINTERFACE");

Interface looks something like:

class JavaScriptInterface {
    public void inject(String html) {
        // Here you will get the Javascript executed
    }
}

Where your client injects the JS:

private class TestWebViewClient extends WebViewClient {

    @Override  
    public void onPageFinished(WebView view, String url) {
        String javascript = "javascript:window.MYJSINTERFACE.inject(document.getElementById('yourlink').href = "+link+");";

        // Inject Javascript in the URL already loaded
        webBrowser.loadUrl(javascript);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You have to create your own class which contains the link your want to insert : addJavascriptInterface.

 class JavascriptUrlObject {
    @JavascriptInterface
    public String toString() { return "http://the-url-to-insert.com"; }
 }
 webView.addJavascriptInterface(new JavascriptUrlObject (), "injectedObject");
 webView.loadData("", "text/html", null);
 webView.loadUrl("javascript:alert(injectedObject.toString())");

In this example, it just opens an alert, but you can do what you want with it in your page.

Look at this link if it can help you : Android addJavaScriptInterface - Code Project.

Comments

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.