lAxxx

最近学习Chrome extension开发时遇到了一些问题,如background怎么与contentscript进行交互,怎么调用jQuery等等

background中引用jQuery

:::javascript
"background": {
  "scripts":["background.js","jquery.min.js"]
}

直接在manifest.json中进行申明.

网上有种方法是将background申明为background.html,然后在background.html中引用background.jsjquery.js,可行但是不优美.

userscript中引用jQuery

:::javascript
chrome.tabs.executeScript(tabId, { file: "jquery.min.js" }, function() {
  chrome.tabs.executeScript(tabId, { file: "contentscript.js" });
});

这里使用了一个小hack,在background.js中使用chrome.tabs.executeScript方法依次调用jQuerycontentscript.js.

background和contentscript进行交互

contentscript:

:::javascript
chrome.extension.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

background:

:::javascript
chrome.extension.onMessage.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"});
  });

background发给contentscript略有不同,请参考Message Passing.

Posted on 2012-12-13 00:00