Why Webnavigation Listener Failed For Some Websites?
I am trying to use chrome extension to get some data from web of science. In one step, I want to create a new tab and wait until it loaded. So I add a webNavigation Listener after
Solution 1:
The main problem is that urlMatches
is a regular expression in RE2 syntax as you can see in the documentation so various special symbols in the URL like ?
are interpreted differently. Answer : use urlEquals
or other literal string comparisons.
There are other problems:
- The API is asynchronous so the tabs are created and queried later in the future in no predictable sequence. Solution: use the callback of create().
- All tabs are reported in webNavigation listener, not just the active one, so theoretically there's a problem of two identical URLs being reported in different tabs. Also the API filtering parameter cannot handle URLs with
#hash
part Solution: remember the tab id you want to monitor in a variable and compare it in the listener, and explicitly strip #hash part in the filter. - The site may redirect the final URL of the page so it may not get reported due to your filter. Solution: specify only the host name in the filter.
- The tab that sends you messages or performs navigation may be inactive. Solution: use the tab id in the listener's parameters.
chrome.browserAction.onClicked.addListener(tab => {
chrome.tabs.sendMessage(tab.id, {message: 'clicked_browser_action'});
});
var link = '...............';
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.joke === 'content initial') {
chrome.tabs.create({url: link}, tab => {
chrome.webNavigation.onCompleted.addListener(functiononCompleted(info) {
if (info.tabId === tab.id && info.frameId === 0) {
chrome.webNavigation.onCompleted.removeListener(onCompleted);
chrome.tabs.sendMessage(tab.id, {message: 'to content'});
console.log('listener succeeded');
}
}, {
url: [{urlPrefix: newURL(link).origin + '/'}],
});
});
}
});
Notes:
- Avoid declaring
content_scripts
in manifest.json for all URLs if you only need processing on demand. Use programmatic injection in such cases. - Instead of alert() use the proper debugging in devtools like breakpoints or
console.log()
of the background page (more info).
Post a Comment for "Why Webnavigation Listener Failed For Some Websites?"