前言
最近有个需求,是在浏览器插件中获取 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.
一、两个 JS 文件,通过 postMessage 传递消息
1. 方案思路
- 新建两个
js
文件,index.js
和lucky.js
- 在
content_scripts
中嵌入index.js
文件 - 在
index.js
中通过script
标签,嵌入lucky.js
- 在
index.js
中通过window.addEventListener('message')
监听消息 - 在
lucky.js
中通过window.postMessage
进行消息传递 - 在
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
const init = () => {
const script = document.createElement('script')
script.src = chrome.runtime.getURL('lucky.js')
document.head.appendChild(script)
// 监听从页面上下文发回的消息
window.addEventListener('message', (event