问题
Although issues with shouldOverrideUrlLoading() are well discussed in SO (I probably read most of them), I still didn't find a solution to what seems to me such a generic problem, that I believe has been solved.
The QUESTION: How to stop in shouldOverrideUrlLoading() for external links, e.g. "http://www.example.com", for pages I loaded with webView.loadDataWithBaseURL(), where baseUrl is "file:///..."?
My override method for shouldOverrideUrlLoading() is not called when external links are touched (clicked). Here it says " URLs that can't be resolved against the base URL are dropped on the floor (you won't get any callbacks for them, neither shouldOverrideUrlLoading nor onPageStarted)." Android developer site says here that "If you loaded the page by calling ... loadDataWithBaseURL(), then you will receive the shouldOverrideUrlLoading() callback for this type of link on the page." This is my code:
public void loadEpub(final EpubInfo epubInfo)
{
post(new Runnable()
{
@Override
public void run()
{
epubBaseUrl = "file://" + epubInfo.path;
if (!epubBaseUrl.endsWith("/"))
epubBaseUrl += "/";
String path = epubBaseUrl + epubInfo.baseUrl;
String page = generatePage(epubInfo);
EpubWebView.super.loadDataWithBaseURL(path, page, "text/html", "UTF-8", null);
}
});
}
where my baseUrl (path) is "file:///storage/sdcard0/Android/data/...".
Many thanks in advance.
回答1:
Pinpointed the problem, and found a solution.
If your page runs in an iframe, clicking on external (http://www...) links does NOT trigger shouldOverrideUrlLoading()! Unless you add target="_top"
So there are at least 2 possible solutions:
1) if you can, run without an iframe
2) if you add to each href, target="_top", shouldOverrideUrlLoading() WILL BE triggered.
I went for solution 2). The following JavaScript code adds the target attribute to each link.
function change_links_target()
{
var all_document_links = mFrameDocument.getElementsByTagName("a");
for (i = 0; i < all_document_links.length; i++){
all_document_links[i].setAttribute("target", "_top");
}
}
来源:https://stackoverflow.com/questions/32401772/shouldoverrideurlloading-not-called-for-external-links-from-iframe