在编写Chrome的一个插件,查询PR值的时候,发现网络访问请求了两次。
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo,tab) { if ("loading"!=tab.status)return; var url = tab.url; console.log("tab.url"+tab.url); if(url != undefined) { //do something } });
以前知道按F5刷新页面onUpdated
这个事件会触发两次。
- 一次是
loading
的的时候 - 一次是
completed
的时候
所以使用了if ("loading"!=tab.status)return;
来进行过滤两次的问题。
注意,新建一个tab页面的时候、进入新的链接(打开新的页面),这个opUpdated事件也是会被触发的。
虽然我使用了tab.status != “loading”来进行过滤两次的问题。但是还有一个问题。每次F5刷新页面,下面的代码只运行了一次,但是新建tab页面的时候、进入新的链接的时候,下面的代码居然运行了2次!
我在跟踪的过程中发现,这两种情况(新建tab页面、进入新的链接)下导致运行两次是因为favicon.ico
这个文件。原来浏览器的tab页面每次更新url,都会去访问favicon.ico这个文件,每次访问都会触发这个事件。
提示:favicon.ico位于网站的根目录下方。比如我的是http://www.chenyudong.com/favicon.ico
,这个文件在浏览器的tab页面的图标上显示。我的是。
所以在tab更新url的时候,会有下面的三种情况
- 访问url,触发事件,loading
- 访问favicon,触发事件
- 访问url结束,触发事件,complete
我们来看看changeInfo
、tab
这两个变量在这三种情况下的信息
//第一种 访问url,触发事件,loading changeInfo = {status: "loading", url: "http://www.chenyudong.com/"} tab = { active: true height: 992 highlighted: true id: 3598 incognito: false index: 39 pinned: false selected: true status: "loading" title: "http://www.chenyudong.com/" url: "http://www.chenyudong.com/" width: 1846 windowId: 1955 } //第二种 访问favicon,触发事件 changeInfo = {favIconUrl: "http://www.chenyudong.com/favicon.ico"} tab = { active: true height: 992 highlighted: true id: 3598 incognito: false index: 39 pinned: false selected: true status: "loading" title: "http://www.chenyudong.com/" url: "http://www.chenyudong.com/" width: 1846 windowId: 1955 } //第三种 访问url结束,触发事件,complete changeInfo = {status: "complete"} tab = { active: true favIconUrl: "http://www.chenyudong.com/favicon.ico" height: 992 highlighted: true id: 3598 incognito: false index: 39 pinned: false selected: true status: "complete" title: "东东东 陈煜东的博客" url: "http://www.chenyudong.com/" width: 1846 windowId: 1955 }
通过查看,我们可以发现,只有一次在访问url的时候,changeInfo会有url这个字段,所以可以利用这个字段来判断,让onUpdate里面的代码对每个url只运行一次。
//以后就使用下面的代码啦 chrome.tabs.onUpdated.addListener(function(tabId, changeInfo,tab) { if( changeInfo.url == undefined)return; var url = tab.url; console.log("tab.url"+tab.url); if(url != undefined) { // do something } });
声明:未经允许禁止转载 东东东 陈煜东的博客 文章,谢谢。如经授权,转载请注明: 转载自东东东 陈煜东的博客
发表评论