谷歌插件流程:第三回
前面我们通过两篇文章,介绍了一个插件的完整开发过程。本文,我们从更加细致的层面,梳理下开发谷歌插件的必知规则
先看看我们的manifest.json文件内容
{
"name": "Ta-da",
"description": "zhihu_small_video_down",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage", "activeTab", "scripting"],
"action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["popup.js"],
"all_frames": true,
"run_at": "document_end"
}
],
"icons": {
"128": "/images/icon.png"
}
}
有三个比较重要的字段指定:background的service_worker,content_scripts的js,分别对应我们的background.js及["popup.js"],两者执行顺序按照介绍顺序,确定js。action的default_popup确定插件界面,事例为popup.html。
js注入执行
在插件的小界面上,我们可以鼠标右键打开一个额外的控制台。由此可见,其与浏览器本身是相互隔离的。那么在小界面的操作,是如何跟当前标签页通信的?
我们在介绍video插件的时候有介绍过,就是js注入。流程: 在界面中点击按钮后,首先获取目标标签id,再给一个逻辑处理函数,塞入executeScript中,执行注入操作。注意,执行逻辑函数时的运行环境,会切换到目标页面的渲染环境中。这样我们就可以执行获取dom等的操作。
代码如下:
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
function: downloadVideo,
},
() => {
console.log('dadadad')
}
);
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
