前言
最近有个需求,是在浏览器插件中获取 window
对象下的某个数据,当时觉得很简单,和 document
一样,直接通过嵌入 content_scripts
直接获取,然后使用 sendMessage
发送数据到插件就行了,结果发现不是这样滴…
在这里不推荐使用
runtime.executeScript
进行注入,很可能会报错:
Refused to execute inline script because it violates the following Content Security Policy directive: “script-src ‘self’ ‘wasm-unsafe-eval’ ‘inline-speculation-rules’ http://localhost:* http://127.0.0.1:*”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-P5exJBBLYN1KVh+CK9MkXvRal4ZQQu9VaKPvx4JuVLE=’), or a nonce (‘nonce-…’) is required to enable inline execution.
Chrome 浏览器插件获取网页 window 对象(方案一)
一、两个文件,通过 CustomEvent 传递消息
1. 方案思路
- 新建两个
js
文件,index.js
和lucky.js
- 在
content_scripts
中嵌入index.js
文件 - 在
index.js
中通过script
标签,嵌入lucky.js
- 在
index.js
中通过window.dispatchEvent
派发自定义custom event
消息;派发消息的内容为一个函数转换的字符串,函数返回的内容则为你需要获取的window
下的对象值 - 在
lucky.js
中通过addEventListener
监听消息,再通过dispatchEvent
派发消息;监听到对应的custom event
的type
的时候,进行参数函数的执行,通过new Function()
的方式执行,并获取返回值,再进行消息派发到index.js
文件 - 在
index.js
中通过addEventListener
监听消息拿到对应的值 - 在
manifest.json
文件中添加web_accessible_resources
1.1. 方案流程
流程图如下:
2. 获取内容
获取
window
下的MyBlog
字段
window.MyBlog = {
juejin: 'https://juejin.cn/user/2409752520033768/posts',
csdn: 'https://guoqiankun.blog.csdn.net/',
'chrome-blog': {
netlify: 'https://gqk-extension.netlify.app/',
github: 'https://18055975947.github.io/extension/'
}
}
3. 实现代码
3.1. index.js
/**
* index 文件发送消息到 lucky.js 文件
* @param {string} type custom 类型
* @param {any} data 数据
*/
const indexSendMessageToLucky = async (type, data) => {
window.dispatchEvent(new CustomEvent('custom-index-type', {
detail: {
type, data }