1

I'm trying to insert an attribute into an <i> element on a page, which is loaded in Android WebView.

How should it work?

For example, I have m.facebook.com loaded in my WebView. Now I want to add an attribute src="mydata" to every <i> tag. So, in result I will have the same page, but each <i> element now will contain src="mydata" (<i src="mydata"></i>).

How can I do it? Is it even possible?

1 Answer 1

1

The example of JavaScript code you want is below:

var i_tag = document.getElementsByTagName('i');
for (var i = 0; i < i_tag.length; i++) {
    i_tag[i].setAttribute('src', 'mydata');
}

So what you need to do is to call JavaScript function when the webpage loaded via loadUrl()

final WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(webView, url);
        webView.loadUrl("javascript:(function(){" +
                "var i_tag = document.getElementsByTagName('i');" +
                "for (var i = 0; i < i_tag.length; i++) {i_tag[i].setAttribute('src', 'mydata');}" +
                "})();");
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

    }
});

webView.loadUrl("https://m.facebook.com/");
Sign up to request clarification or add additional context in comments.

4 Comments

If this is the right answer try to mark an answer as accepted so others can see it :)
Sorry, but it still doesn't work for me. What I'm trying to do is to add an onclick="ok.performClick(this.style)" attribute to the each i element on a page. But it doesn't work for me. It looks like I'm doing it totally wrong. Here is my code: gist.github.com/sfilmak/3260bd91f7ac240bba407a783b17a522 Thank you!
So the result you want is like this? <i onclick="ok.performClick(this.style)">Some italic text</i>
I wonder why your for loop not using .length and I found that "https://m.facebook.com/" just contain six <i> tag

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.