Issue
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
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?
Solution
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))");
}
}
});
Which works exactly how I want it to
Answered By - nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.