前言

最近有个需求,是在浏览器插件中获取 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 对象(方案一)

Chrome 浏览器插件获取网页 window 对象(方案二)

一、两个文件,通过 CustomEvent 传递消息

1. 方案思路

  1. 新建两个 js 文件,index.jslucky.js
  2. content_scripts 中嵌入 lucky.js 文件和 index.js 文件
  3. index.js 中通过 window.dispatchEvent 派发自定义 custom event 消息
  4. index.js 中通过 addEventListener 监听消息
  5. lucky.js 中通过 addEventListener 监听消息,再通过 dispatchEvent 派发消息

1.1. content_scripts 嵌入 JS 文件

一定要把 lucky.js 文件放在 index.js 文件前面

content_scripts 中添加 lucky.js 的时候需要加上 "world": "MAIN" 字段

world 为枚举类型

  • ISOLATED 默认值

    • 此扩展程序所独有的执行环境
  • MAIN
    • 指定 DOM 的主域,也就是与托管页面的 JavaScript 共享的执行环境

1.2. 方案流程

流程图如下:

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 } }))
return new Promise((res) => {
function handleResponse(e) {
const detail = e.detail
if (detail.type == type) {
window.removeEventListener('custom-lucky-type', handleResponse)
return res(detail.data)
}
}
window.addEventListener('custom-lucky-type', handleResponse)
})
} /**
* 发送消息
*/
const sendMessage = () => {
function getMyBolg() {
return window.MyBlog
}
indexSendMessageToLucky('run-index-fun', {
function: getMyBolg.toString()
}).then((res) => {
console.log('res-->', res)
}).catch((e) => {
console.log('e', e)
})
}
/**
* 初始化
*/
const init = () => { // 插入 button 按钮
const button = document.createElement('button')
button.innerText = '获取数据'
button.id = 'chrome-ext-but'
document.body.appendChild(button)
button.onclick = () => {
sendMessage()
}
// 初始化获取数据
sendMessage()
} // 判断 window.top 和 self 是否相等,如果不相等,则不注入
if (window.top == window.self) {
init()
}

3.2. lucky.js

/**
* 事件监听
*/
window.addEventListener('custom-index-type', async (e) => {
const { type, data } = e.detail
switch (type) {
case 'run-index-fun': {
const fn = new Function(`return (${data.function})(...arguments)`)
const rs = await fn(...(data.args ?? []))
luckySendMessageToIndex(type, rs)
break
}
}
}) /**
* lucky 文件发送消息到 index.js 文件
* @param {string} type custom 类型
* @param {any} data 数据
*/
const luckySendMessageToIndex = (type, data) => {
window.dispatchEvent(
new CustomEvent('custom-lucky-type', {
detail: { type, data, file: 'lucky' }
})
)
}

3.3. manifest.json

{
"manifest_version": 3,
"name": "Get Winddow Object Field",
"version": "1.0",
"description": "Gets the field under window",
"content_scripts": [
{
"js": [
"lucky.js"
],
"matches": ["http://localhost:*/*"],
"run_at": "document_end",
"world": "MAIN"
},
{
"js": [
"index.js"
],
"matches": ["http://localhost:*/*"],
"all_frames": true,
"run_at": "document_end"
}
],
"background": {
"service_worker": "service-worker.js"
},
"host_permissions": [
"http://localhost:*/*"
],
"permissions": [
],
"web_accessible_resources": []
}

3.4. 项目文件结构

.
├── index.html
├── index.js
├── lucky.js
├── manifest.json
└── service-worker.js

3.5. 方案效果

在控制台中选择当前插件,即可查看获取的 window 下的 MyBlog 对象

4. 动态获取数据

4.1. 点击按钮

4.2. 数据返回

5. 代码地址

四、总结

1. 文章总结

  1. 获取当前页面下的 window 对象和 document 对象不一样,需要另外的处理方式
  2. 此次提供了三种方案,核心原理都是嵌入当前页面,通过消息派发和接收来获取数据
  3. 第一种通过 postMessage 的方式更为大家熟悉,自定义 Event 相对偏一点
  4. 三种方案的代码我都上传到 gitee/github 上了

2. 代码地址

引用

Chrome 浏览器插件获取网页 window 对象(方案三)的更多相关文章

  1. 使用 Chrome 浏览器插件 Web Scraper 10分钟轻松实现网页数据的爬取

    web scraper 下载:Web-Scraper_v0.2.0.10 使用 Chrome 浏览器插件 Web Scraper 可以轻松实现网页数据的爬取,不写代码,鼠标操作,点哪爬哪,还不用考虑爬 ...

  2. chrome浏览器插件window resizer调试webapp页面大小

    chrome浏览器插件window resizer可以调整当前浏览器分辨率大小 可以自定义大小,以适合于andorid和iphone设备

  3. Rest Client(Rest接口调试工具,有保存功配置功能) chrome浏览器插件

    Rest Client(Rest接口调试工具,有保存功配置功能) chrome浏览器插件 下载地址 插件的操作很简单,下面是一些简单的实例. 1.安装 在谷歌应用商城搜索postman,如下图1-1所 ...

  4. 用Javascript编写Chrome浏览器插件

    原文:http://homepage.yesky.com/62/11206062.shtml 用Javascript编写Chrome浏览器插件 2010-04-12 07:30 来源:天极网软件频道 ...

  5. chrome浏览器插件开发经验(一)

    最近在进行chrome浏览器插件的开发,一些小的经验总结随笔. 1.首先,推荐360的chrome插件开发文档:http://open.chrome.360.cn/extension_dev/over ...

  6. 还在为百度网盘下载速度太慢烦恼?chrome浏览器插件帮你解决!

    百度网盘已然成为分享型网盘中一家独大的“大佬”了.时代就是这样不管你喜不喜欢,上网总会遇到些百度网盘共享的文件需要下载.然而,百度网盘对免费用户的限速已经到了“感人”的地步了,常常十多KB/秒的速度真 ...

  7. 强烈推荐 10 款珍藏的 Chrome 浏览器插件

    Firebug 的年代,我是火狐(Mozilla Firefox)浏览器的死忠:但后来不知道为什么,该插件停止了开发,导致我不得不寻求一个新的网页开发工具.那段时间,不少人开始推荐 Chrome 浏览 ...

  8. chrome浏览器插件启动本地应用程序

    chrome浏览器插件启动本地应用程序 2014-04-20 00:04:30|  分类: 浏览器插件|举报|字号 订阅     下载LOFTER我的照片书  |     chrome的插件开发这里就 ...

  9. 通过chrome console 快速获取网页连接

    通过chrome console 快速获取网页连接 var ip = document.getElementsByClassName("jDesc"); var str = &qu ...

  10. chrome浏览器页面获取绑定返回顶部动画事件插件

    在chrome浏览器下页面加载: var top = $("body").scrollTop()  ; console.log(top)                      ...

随机推荐

  1. ComfyUI基础篇:为什么要学 ComfyUI?

    前言: 在AI生成图像领域,有许多产品,例如 Midjourney 和 Stability AI 等.为什么要学习 ComfyUI 呢?我斗胆带大家一起分析一下. 目录 1.Midjourney VS ...

  2. 【VMware vCenter】VMware vCenter Server(VCSA) 5.5 版本证书过期问题处理过程。

    之前帮客户处理了一个因证书过期导致 vCenter Server 无法登录的问题,在此记录一下,因为时间过去有点久了,可能会有些地方描述的不是很清楚,所以就当作参考就行.客户环境是一个非常老的 vCe ...

  3. SQL Server 帐号权限管理及C#编程应用(图解)

    昨晚在群里讲解这部分内容,因为好久没操作过了,差点翻车...今天把它整理一下发出来,方便没听明白的小伙伴学习和理解. 我们平时学习数据库时,要么使用sa帐号,要么用windows默认帐号登录,总之都拥 ...

  4. 【js】 reduce、filter、map 数组链式调用求加和

    let data = [ {hierarchy: '香蕉', count: 1}, {hierarchy: '苹果', count: 2}, {hierarchy: '葡萄', count: 3}, ...

  5. ChatGPT的作用(附示例)

    ChatGPT介绍(内容由ChatGPT生成) ChatGPT是一款基于GPT(生成式预测网络)的聊天机器人,它可以根据用户输入自动生成相应的回复. GPT是由OpenAI开发的一种预测网络模型,其中 ...

  6. Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=stock error was 14: curl#6 - "Could not resolve host: mirrorlist.centos.org; 未知的错误"解决yum下载报错

    报错信息 │ (SSH client, X server and network tools) │ │ │ │ ⮞ SSH session to root@192.168.117.166 │ │ • ...

  7. 【Git】下载安装(Linux)

    安装CentOS8貌似有自带Git 可以先查看一下有没有 git --version 有或者没有都行,有的话安装就当是更新 没有就装,yum提供了安装,我们不需要自己压缩包安装了 yum instal ...

  8. 汽车模具设计软件 —— 达索集团的Catia

    相关: https://www.3ds.com/zh/products-services/catia/ Catia是Dassault Systems公司推出的产品造型软件,广泛应用于汽车.航空.机械等 ...

  9. 一个好主板对CPU超频的现实意义————一次超频经历 (z390ws华硕工作站主板+i7-9700k CPU ,Ubuntu18.04.5系统,8核心超频 5.2Ghz以上,单核心满负荷运转可以稳定运行10多分钟后才重启)

    本人于今年2020年1月份在某宝上购买了一款workstation主板,也就是工作站主板,传说中的华硕Z390WS主板(购入价格为3900元),由于当时手里有些小钱,又弄了一个大蝴蝶1350w的电源( ...

  10. A3C与GA3C的收敛性分析

    G-A3C的代码: https://gitee.com/devilmaycry812839668/gpu_a3c 论文: <Reinforcement Learning thorugh Asyn ...