谷歌浏览器插件开发教程2

谷歌浏览器插件控制网页内容的方法

1 首先写配置文件(注意下content_scripts 这个里面的js  是控制页面的js

{
    "name": "todo-plugin",
    "version": "0.9.0",
    "manifest_version": 2,
    "description": "chrome plugin demo",
    "browser_action": {
        "default_icon": "icon.png",
        "default_title": "Todo List",
        "default_popup": "popup.html"
    },
    "content_scripts": [{  //对页面内容进行操作的脚本
         "matches": ["http://*/*","https://*/*"],  //满足什么条件执行该插件 
         "js": ["jquery.min.js","test.js"]
    }] 
    
}

2 然后页面上写test.js

var kw = $('#kw');
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.action == "send") {
            kw.val(request.keyword)
            sendResponse({state:'填写成功!'});
        }
      
    }
);

3  插件html

<!doctype html>

<html>

<head>

<meta http-equiv="content-type" content="txt/html; charset=utf-8" />

<title>Document</title>


</head>

<body>


<script src="jquery.min.js"></script>
<script src="test1.js"></script>


</body>

</html>

test1.js 给页面发送请求 到test.js

$(function(){
  chrome.tabs.query({active:true, currentWindow:true}, function (tab) {//获取当前tab
            //向tab发送请求
            chrome.tabs.sendMessage(tab[0].id, { 
                action: "send",
                keyword: "关键字"
            }, function (response) {
                console.log(response);
            });
        });
})

好了 打开www.baidu.com 然后点击图标测试 是不是直接搜索关键字了

ps:如果报错  Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.  那是test.js里面的代码运行出错了 如果不是运行百度页面就会这样 因为匹配不到元素

下期内容 网页内容控制插件方法

猜你喜欢

转载自www.cnblogs.com/newmiracle/p/11921426.html