Hello World

Chrome Extension Development

Difference between similar API

chrome.runtime.sendMessage VS chrome.tabs.sendMessage

  • chrome.runtime.sendMessage

    Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender’s frame), or runtime.onMessageExternal, if a different extension.Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.

  • chrome.tabs.sendMessage

    Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension.

Tips

  1. popup page 的生存时间
    popup.js 仅在 popup page 打开时运行,一旦关闭就结束运行。
    值得注意的是:popup.js 调用 chrome.runtime.sendMessage() 时,如果popup.js中存在 runtime message listener,那么这个listener会最先反应,并且ignore other listeners in the extension

  2. manifest file 中的 permission
    只有声明了 activeTab的permission 才能使用 chrome.tabs.executeScript()

  3. popup page 相当于一个新的tab
    popup page是有自己的popup.htmlpopup.js

  4. chrome.tab.* 是关于tabs的API

  5. 如果没有在 manifest 里声明 content_scripts run at document start,那么在content script 里的 doument.addEventListener('DOMContentLoaded', function (){...}是没有用的,因为默认加载content script的时间是在tab加载完之后,已经错过了 DOMContentLoaded Event

  6. content script 会在每次new page加载时加载,注意不是new tab 也就是说即便是在同一个tab内点击链接跳转(没有在新标签页打开),content script也会再加载一次。

  7. jQuery selector 中 a = $("tag:contains('something')")选中 innerHTML含有’something’的tag的元素。返回指是一个jQuery Object,不是直接的DOM元素,要用a[0]得到DOM元素,而DOM元素要转换为jQuery对象可以使用 $(a[0])