我正在开发的 Android 应用程序的大部分功能都依赖于网页。当用户单击通常会调用 window.open 的链接时,我希望它调用自定义函数。这样它就会阻止应用程序打开浏览器窗口,从而破坏了使用应用程序的错觉。我已经设置了一个 JavaScriptInterface 来替换它在页面中找到的所有 window.open 实例。我现在遇到的问题是外部 javascript 文件。它的功能与此非常相似
function LoadItem(url,title)
{
window.open("/items.html?item=" + url + "&title=" + EncodeString(title), "song: " + title);
}
我想修复它,所以改为:
function LoadItem(url,title)
{
window.LinkFixer.openInNewTab("/items.html?item=" + url + "&title=" + EncodeString(title), "song: " + title);
}
这是我迄今为止的代码,应该为我做这件事。
public String processPage(String html)//called once the page has been loaded
{
html = html.replace("window.open","window.LinkFixer.openInNewTab").replace("OpenSong","window.LinkFixer.openSong");
String[] lines = html.split("\n");
html = "";
for(int i=0;i<lines.length;i++)
{
if(lines[i].contains("<script")&&lines[i].contains("src="))
{
lines[i] = getJs(lines[i]);
}
html += lines[i];
}
return html;
}
private String getJs(String line)//gets the javascript, fixes it so it's safe for the app, then returns it as inline rather than embeded
{
String jsFileName = line.replace("\"","'").replace("<script type='text/javascript' ","").replace("src=","").replace(">","").replace("'","").trim();
//public static String makeGetRequest(String url,boolean oneLine)
System.out.println(jsFileName);
String targetUrl = "/BrowserControl/"+jsFileName;
System.out.println(targetUrl);
String jsFile = ShowWebInterface.makeGetRequest(targetUrl,false);
Log.d("OrigFile"+jsFileName,jsFile);
jsFile = jsFile.replace("window.open","window.LinkFixer.openInNewTab").replace("OpenSong","window.LinkFixer.openSong").replace("function window.LinkFixer.openSong(url, title)","window.LinkFixer.openSong");
Log.d("NewFile"+jsFileName,jsFile);
return "<script type=\"text/javascript\">\n"+jsFile;
}
对于第一次点击,它有效。对于此后的任何内容,它都会在我的应用程序控制之外的浏览器窗口中加载页面。我遇到问题的页面确实使用了ajax,所以我相当确定这会导致某种问题。我认为浏览器仍然会调用 onProgressChanged 方法,但我可能是错的。
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))");
}
}
});
我有什么遗漏的吗?有什么方法可以劫持ajax的回调函数吗?或者也许是我忽略的其他东西。
最佳答案
我相信您应该使用shouldOverrideUrlLoading(...)
How to make links open within webview or open by default browser depending on domain name?似乎有一个很好的例子。
关于java - 替换来自 Android WebView 的外部 javascript 文件中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9998642/