美文网首页程序员Web前端之路让前端飞
动手做自己的 chrome Extension

动手做自己的 chrome Extension

作者: zidea | 来源:发表于2019-06-07 18:21 被阅读21次
chrome

建立项目

  • 创建一个文件夹
  • name 定义扩展名称
  • version 给出扩展的版本号
  • manifest_version 给出我们版本号
{
    "manifest_version": 2,
    "name": "zidea",
    "description": "hello chrome extension",
    "version": "1.0.0"
 }

然后在浏览器地址输入

chrome://extensions/

进入扩展程序页面

扩展程序
在页面中开启开发者模式,然后点击加载已解压的扩展程序导航到项目目录下添加即可
开启开发者模式
"content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["content.js"]
    }]
contents文件
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button>popup</button>
</body>

</html>

popup.js

document.addEventListener('DOMContentLoaded',()=>{
    const btn = document.querySelector('button');
    btn.addEventListener('click',onClick,false);
    function onClick(){
        chrome.tabs.query({currentWindow:true, active:true}, 
            function(tabs){
                chrome.tabs.sendMessage(tabs[0].id,'hi')        
            }
        )
    }
},false);
  • 通过querySelector获取 button 元素,为 button 添加点击事件
  • 在 onClick 事件我们希望获取页面内容,如果想要获取页面内容,就需要和 content.js 进行通讯。
    通过 chrome 对象提供方法找到当前处于活动的页面 chrome.tabs.query,传入对象
    {currentWindow:true, active:true}用于限定范围,然后通过回调函数可以获得 tabs对象,就可以通过 id 确定给哪个 tab 发送消息。

content.js

chrome.runtime.onMessage.addListener(function(request){
    alert(request);
})

在 content 中可以就收消息,然后弹出从 popup.js 发送过来消息

通讯录

这是一个 react 做的项目,这是一个通讯录的列表,在列表中有重复名字,所以我们通过 content.js 来获取名字为 madame 的用户个数,然后将统计结果发送给 popup 文件

document.addEventListener('DOMContentLoaded',()=>{
    const btn = document.querySelector('button');
    btn.addEventListener('click',onClick,false);
    
    function onClick(){
        chrome.tabs.query({currentWindow:true, active:true}, 
            function(tabs){
                chrome.tabs.sendMessage(tabs[0].id,'hi',setCount)        
            }
        )
    }

    function setCount(res){
        const div = document.getElementById('message');
        div.textContent = `${res.count} madame`;
    }
},false);

我们在sendMessage方法的最后一个参数是一个回调函数将然后setCount将从 content.js 返回的值输出到 popup.html 中

// alert('content')
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    const re = new RegExp('madame','gi');
    const matches =
        document.documentElement.innerHTML.match(re);
    sendResponse({count:matches.length});
})
  • 统计好结果后通过 sendResponse 将 count 结果发送回给 popup.js 来显示出其结果。


    消息
    chrome-extension

相关文章

网友评论

    本文标题:动手做自己的 chrome Extension

    本文链接:https://www.haomeiwen.com/subject/izymxctx.html