核心提示:background可以包含三种属性,分别是 scripts 、page 和 persistent如果指定了 scripts 属性,则Chrome会在扩展启动时自动创建一个包含所有指定脚本的页面 如果...
background可以包含三种属性,分别是 scripts 、page 和 persistent
如果指定了 scripts 属性,则Chrome会在扩展启动时自动创建一个包含所有指定脚本的页面 如果指定了 page 属性,则Chrome会将指定的HTML文件作为后台页面运行 通常我们只需要使用 scripts 属性即可,除非在后台页面中需要构建特殊的HTML——但一般情况下后台页面的HTML我们是看不到的 persistent属性定义了常驻后台的方式(默认为true)——当其值为true时,表示扩展将一直在后台运行,无论其是否正在工作;当其值为false时,表示扩展在后台按需运行,这就是Chrome后来提出的 Event Page。 Event Page 可以有效减小扩展对内存的消耗,如非必要,请将persistent设置为false。小项目
检测博客是否在线
manifest
{ "manifest_version": 2, "name": "Blog在线状态", "version": "1.0", "description": "监视Blog是否在线", "icons": { "16": "images/icon16.png", "48": "images/icon48.png", "128": "images/icon128.png" }, "browser_action": { "default_icon": { "19": "images/icon19.png", "38": "images/icon38.png" } }, "background": { "scripts": [ "js/status.js" ] }, "permissions": [ "https://cuiqingcai.com/" ] }
status.js
function httpRequest(url, callback){ var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { callback(true); } } xhr.onerror = function(){ callback(false); } xhr.send(); } setInterval(function(){ httpRequest('https://cuiqingcai.com/', function(status){ chrome.browserAction.setIcon({path: 'images/'+(status?'online.png':'offline.png')}); }); },5000);
每5秒检测一下请求状态,因为没有 UI所以不考虑html