Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 716
  • Last Modified:

Execute method in JavascriptInterface after page has finished loading

I would like to be able to do some processing on the html and javascript of a page before it is presented to the user of my app. The page uses window.open for all the links and that causes a new browser window, not controlled by my app, to be opened, which destroys to illusion of using an app. This is what I have right now, which I think will work for the most part.

    class LinkFixer
    {
        static HashMap<String,String>pages = new HashMap<String,String>();//static so multiple pages can access it

        public void processPage(String html)
        {
            html = html.replace("window.open","LinkFixer.openInNewTab");
        }

        public void openInNewTab(String url, String targetName)
        {
            if(!pages.containsKey(targetName))//targetName is unique for every link
            {
                pages.put(targetName,url);
                //add new tab to my TabHost, which will contain a WebView with page from url loaded
            }
            
            //move user to tab
        }
    }
    WebView browser = (WebView)findViewById(R.id.browser);
    browser.getSettings().setJavaScriptEnabled(true);

    browser.addJavascriptInterface(new LinkFixer(), "LinkFixer");
    browser.loadUrl("http://serverIP:port/mobilecontrol.html");
    //something to make the browser execute LinkFixer.processPage goes here

Open in new window


The problem I'll have with it, is that I'm not sure how I would make the page execute LinkFixer.processPage when the page finishes loading. Other than that, I think the code will work. Any suggestions?
0
Curtis Long
Asked:
Curtis Long
1 Solution
 
Curtis LongAuthor Commented:
I wound up making a new WebChromeClient and overriding the onProgressChanged method to fix the links after newProgress is 100 or greater.

    browser.setWebChromeClient(new WebChromeClient()
		{
			public void onProgressChanged(WebView webView, int newProgress)
			{
				super.onProgressChanged(webView,newProgress);
				if(newProgress >= 100)
				{
					System.out.println("Done loading");
					browser.loadUrl("javascript:document.getElementsByTagName(\"html\")[0].innerHTML = window.LinkFixer.processPage((document.getElementsByTagName(\"html\")[0].innerHTML))");
				}
			}
		});

Open in new window


Which works exactly how I want it to
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now