当前位置: 首页 > news >正文

chrome extensions mv3通过content scripts注入/获取原网站的window数据

开发插件的都知道插件的content scripts和top window只共享Dom不共享window和其他数据,如果想拿挂载在window的数据还有点难度,下面会通过事件的方式传递cs和top window之间的数据写一个例子

代码

manifest.json

这里只搞了2个js,content.js是content scripts,main.js是在top window里运行的

{
  "version": "0.0.1",
  "author": "apades",
  "name": "ext-hack",
  "description": "",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_end",
      "all_frames": true
    },
    {
      "matches": ["<all_urls>"],
      "js": ["main.js"],
      "run_at": "document_end",
      "world": "MAIN"
    }
  ]
}

content.js

async function sendExtMessage(type, data) {
  window.dispatchEvent(new CustomEvent('ext-req', { detail: { type, data } }))

  return new Promise((res) => {
    function handleResponse(e) {
      const detail = e.detail
      if (detail.type == type) {
        window.removeEventListener('ext-res', handleResponse)
        return res(detail.data)
      }
    }
    window.addEventListener('ext-res', handleResponse)
  })
}

// 暴露到content script的window里测试
window.sendExtMessage = sendExtMessage

main.js

window.addEventListener('ext-req', async (e) => {
  const { type, data } = e.detail

  switch (type) {
    case 'run-code': {
      let fn = new Function(`return (${data.function})(...arguments)`)

      let rs = await fn(...(data.args ?? []))
      sendExtResponse(type, rs)
      break
    }
  }
})

function sendExtResponse(type, data) {
  window.dispatchEvent(
    new CustomEvent('ext-res', {
      detail: { type, data },
    })
  )
}

运行测试

首先我先在top window里随便写个window.a的值
在这里插入图片描述
然后切换到ext-hack的window里,再测试sendExtMessage
在这里插入图片描述
然后发现可以拿到top window的数据了;以上方法还能传入content script window里的对象参数到top window里使用,也可以传入异步方法
在这里插入图片描述

最后要说的

通过事件里互相传的数据会经过插件内部的序列化,地址、Object.defineProperty都是不共享的。而且这个方法相较于script标签插入,可以绕开doc response的Content-Security-Policy

相关文章:

  • Redis实现API访问频率限制
  • [FineReport]安装与使用(连接Hive3.1.2)
  • ORACLE Redo Log Buffer 重做日志缓冲区机制的设计
  • Midjourney 生成油画技巧
  • Neo4j最新安装教程(图文版)
  • 美容店预约小程序搭建流程
  • 【算法笔记】求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
  • Java集成Onlyoffice以及安装和使用示例,轻松实现word、ppt、excel在线编辑功能协同操作,Docker安装Onlyoffice
  • 深度学习 二:COVID 19 Cases Prediction (Regression)
  • 03-Zookeeper客户端使用
  • Java进阶篇--网络编程
  • 【分布式云储存】Springboot微服务接入MinIO实现文件服务
  • 用go实现http服务端和请求端
  • 【数据结构】选择排序 堆排序(二)
  • POSIX
  • Flutter开发之Package与Plugin
  • 基于 SpringBoot 2.7.x 使用最新的 Elasticsearch Java API Client 之 ElasticsearchClient
  • el-menu 导航栏学习(1)
  • Linux下安装MySQL
  • 餐饮外卖配送小程序商城的作用是什么?
  • 廊坊市长:健全依法决策和决策纠错机制,把群众满意作为工作准绳
  • 中国房地产报:以改促治实现楼市多难并解
  • 两大跨国巨头称霸GLP-1市场,国产减肥药的机会在哪?
  • 昆明盘龙区一火灾调查报告公布:老人火盆取暖引燃房屋致身亡
  • 伊守亮回国加盟川大,长期致力于化工能源环境前沿领域研究
  • 肯尼亚总统鲁托将访华,外交部:中肯两国元首将举行会谈