chrome扩展开发实战入门之一-hellocrx

后记:在写这篇文章时,我还没搞懂chrome扩展的基本原理。后来才明白,最简单(且实用)的扩展只需要manifest.json和content_scripts.js两个文件,无需background.js等。content_scripts中的代码会按照manifest.json中指定的匹配网址(matches)和运行时间(run_at)来执行,从而对网页的DOM进行操作。而且为了方便,还可以在manifest.json中引入jquery进行操作。可参考下一篇文章。

环境:win7+chrome77

1、新建目录,名为hellocrx    ;其中,新建文件manifest.json,内容为:

{
  "manifest_version": 2,
  "name": "hellocrx",
  "version": "1.0.0",  
  "description": "crx入门学习",
    "content_scripts": [
    {
    "matches": ["<all_urls>"],
    "js": ["mycontent.js"],
    "run_at": "document_end",
    "all_frames": true
    }
  ],
  "permissions": [
    "bookmarks", "http://*/*", "https://*/*"
  ]
}

再新一建一个空的文件,名为:mycontent.js

好了,chrome扩展已经完成了。现在:

(1)访问:chrome://extensions/  

(2)打开“开发者模式”开关,点击“加载已解压的扩展程序,选择您所建立的hellocrx目录。

hellocrx扩展已经出现在url地址栏右侧了,点击扩展图标会有弹出菜单。可以关闭开发者模式了。

2、为了实现交互,现在给chrome浏览器增加右键菜单

(1)修改manifest.json中permissions字段为:

  "permissions": [
    "bookmarks", "http://*/*", "https://*/*","contextMenus","tabs"
  ]

与manifest_version字段平级增加background字段:

    "background":
    {
        // 2种指定方式,如果指定JS,那么会自动生成一个背景页
        //"page": "background.html"
        "scripts": ["background.js"]
    },

(2) background.js内容为:

chrome.contextMenus.create({
    title: "测试右键菜单",
    onclick: function(){alert('您点击了右键菜单!');}
});

(3)注意保存文件,然后打开chrome://extensions/   

点击hellocrx扩展上的刷新图标,重新加载扩展。(注意:如果您修改的是chrome扩展的manifest.json配置项,一定要在chrome的扩展管理中删除当前扩展 然后重新加载才行。更新是没有用的

此时,在网页上点鼠标右键,将弹出提示。但是中文是乱码(我想解决办法应该是自己写background.html,指定页面编码。我想这也说明此时脚本运行在background页面中的。)

3、background(以及popup)中无法直接访问页面DOM。就需要用到有权限与网页交互的content_scripts到,也就是我们在manifest.json中指定的mycontent.js

(1)修改background.js,使得点击右键时调用mycontent.js,以便操作DOM

chrome.contextMenus.create({
    title: "测试右键菜单",    
});
// "activeTab" permission is sufficient for this:
chrome.contextMenus.onClicked.addListener(function(info, tab){
  chrome.tabs.executeScript(tab.id, {file: "mycontent.js"})
});

(2)修改mycontent.js内容如下:

document.body.style.backgroundColor="black";

重新加载插件,在页面上点右键菜单,发现页面背景变成黑色了。

(这里有个问题:重新刷新网页后,背景还是黑色。解决办法是关闭插件后再刷新。)

4、为了更方便调试查看操作效果,还是不用右键菜单了。改为直接点击插件来执行mycontent.js

即让background页和content页实现相互通信 

(1)manifest.json 

{
  "manifest_version": 2,
  "name": "hellocrx",
  "version": "1.0.0",  
  "description": "crx入门学习",
  "content_scripts": [
    {
    "matches": ["<all_urls>"],
    "js": ["mycontent.js"],
    "run_at": "document_end",
    "all_frames": true
    }
  ],
  "background":
    {
      "scripts": ["background.js"]
    },
  "browser_action": {
    "default_title": "mycrx测试"
    },
  "permissions": [
    "bookmarks", "http://*/*", "https://*/*","contextMenus","tabs","activeTab"
  ]
}

 (2)background.js

chrome.browserAction.onClicked.addListener(function(tab) {
  // No tabs or host permissions needed!
  console.log('Turning ' + tab.url + ' green!');
  alert("crx was clicked and url is:" + tab.url);
chrome.tabs.query(
    {active: true, currentWindow: true}, 
    function(tabs) {
          chrome.tabs.sendMessage(
            tabs[0].id, 
            {greeting: "hello"}, 
            function(response) {
                    console.log(response.farewell);
        });
});
});

(3)mycontent.js:

alert("mycontent start run"); 
chrome.runtime.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"});
      //访问页面的DOM
      document.body.style.backgroundColor="green";
      document.getElementById("kw").value="crx"
});

删除插件,重新从源文件目录加载。

效果是:a. 打开网页时,会弹窗显示"mycontent start run"。

              b.点击地址栏右侧的插件图标,会弹窗显示"crx was clicked and url is……"。 并且网页背景变成绿色(有的网页可能看不清)

              c.打开背景变绿的网页的console,会看到“from the extension”

              d.在chrome://extensions/打开hellocrx的背景页,会看到“goodbye”

               e.如果是在百度的搜索页面,还会自动在搜索框内写入“crx”

这样,就实现了点击扩展图标,执行background页中的JS,向Content页发消息;然后Content页接到消息,去操作DOM。

然而,注意一个bug:

重新加载扩展后,要刷新已打开的网页,才能再次点击扩展图标,否则扩展会出现错误。在chrome://extensions/页点击扩展图标也会出错。

 修改代码后,测试扩展的正确方法是:每次刷新先网页,后击扩展图标执行。

参考:https://www.cnblogs.com/liuxianan/p/chrome-plugin-develop.html

http://open.chrome.360.cn/extension_dev/windows.html#apiReference

http://www.ptbird.cn/category/chrome-extensions/

https://www.cnblogs.com/he-bo/p/9963540.html

https://www.cnblogs.com/champagne/p/4848520.html

以及我之前写的https://www.cnblogs.com/pu369/p/6381560.html

原文地址:https://www.cnblogs.com/pu369/p/12036717.html