當然也可以通過屬性"page"替換"scripts"來引入.html文件,不過scripts和page只能兩選其一,如下所示:
"background": { "page": "background.html" }
顧名思義,可以理解爲背景頁面腳本,或者直接解釋爲後臺腳本。background用來處理插件本身的一些邏輯,比如插件加載時需要執行的處理,運行中需要統一維護的數據等等,background只會在插件加載的時候運行一次,你可以在這個過程中讓它綁定一些運行中的事件。比如background中可以直接訪問chrome.browserAction對象來設置和定義browserAction,如:
chrome.browserAction.onClicked.addListener(function(){
......
});
{
"browser_action": {
"default_icon": "icon19.png",
"default_title": "Google Mail",
"default_popup": "popup.html"
}
}
var bg = chrome.extension.getBackgroundPage();
bg.testBG();
chrome.tabs.executeScript(null, {code:"document.body.style.backgroundColor=blue"});
var element = document.body.firstChild;
var div = document.createElement("div");
document.body.insertBefore(div, element);
chrome.tabs.sendRequest(tab.id, data, function(data) {});
chrome.extension.sendRequest(data, function(data) {});
以下是官方文檔中的例子:
一次簡單的請求
如果你僅僅需要給你自己的擴展的另外一部分發送一個消息(可選的是否得到答覆),你可以簡單地使用chrome.extension.sendRequest()或者chrome.tabs.sendRequest()方法。這個方法可以幫助你傳送一次JSON序列化消息從content script到擴展,反之亦然。如果接受消息的一方存在的話,可選的回調參數允許處理傳回來的消息。
像下面這個例子一樣,可以從content script 發起一個請求:
contentscript.js
================
chrome.extension.sendRequest({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
傳遞一個請求到擴展很容易,你需要指定哪個標籤發起這個請求。下面這個例子展示瞭如何指定標籤發起一個請求。
background.html
===============
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
接受消息的一方,需要啓動一個chrome.extension.onRequest事件監聽器用來處理消息。這個方法在content script和擴展中都是一樣的。這個請求將會保留直到你做出了迴應。下面的這個例子是一個很好的做法調用一個空對象請求然後得到答覆的例子。
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({}); // snub them.
});
小提示:如果多個頁面都發起了相同的請求,都在等待答覆,只有第一個發起請求的頁面會得到響應,其他的將會被忽略。
content script除了跟background可以交互,跟web page本身也可以有信息交互。一方面content script可以直接訪問page的dom,同時還可以通過dom的Event來跟頁面進行交互。
document.addEventListener("EventName",function() {});
var ev = document.createEvent('HTMLEvents');
ev.initEvent('EventName', false, false);
document.dispatchEvent(ev);
"page_action" : {
"default_icon" : "icon.png",
"default_title" : "Page Action"
}
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (tab.url.indexOf("mail") > -1) {
chrome.pageAction.show(tabId);
}
});
"plugins": [
{ "path": "plugin1.dll", "public": true },
{ "path": "plugin2.dll" }
]
<embedtype="application/x-plugin1"id="pluginId">
<script>
var plugin = document.getElementById("pluginId");
var result = plugin.PluginMethod(); //調用plugin中定義的方法
</script>