chrome extension无法获取window对象

背景见上一篇博客修改网页内容的方法

上一篇博客之后,我要修改的网页有一个新改版,然后有个数据存在了window中,我直接在js中使用window.xxx发现无法获取。所以有本文。

https://juejin.cn/post/7145749643316428830

https://onelinerhub.com/chrome-extension/window_object#:\~:text=chrome-extension How to access or modify window object,%3D 'console.log (window)%3B'%3B (document.head||document.documentElement).appendChild (script)%3B ctrl %2B c

搜了一下发现有两种方法,如上,大概就是:

方法1

javascript 复制代码
var script = document.createElement('script');
script.textContent = 'console.log(window);';
(document.head||document.documentElement).appendChild(script);

出现报错:

bash 复制代码
extensions_version_page.js:6 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-XnQUOdrKm+cYqdkT/ljnkhjaYaitt2Xh3uRQxH/M9z0='), or a nonce ('nonce-...') is required to enable inline execution.

方法2

json 复制代码
{
  "name": "yeshen_extresion",
  "version": "1.0",
  "description": "yeshen test",
  "manifest_version": 3,
  "web_accessible_resource": [
    {
      "resources": [
        "assets/*",
        "js/contentScript.js"
      ]
    }
  ],
  "content_scripts": [
    {
      "matches": [
        "https://innovation.pm.netease.com/v6/issues/*",
        "https://web.pm.netease.com/v6/issues/*",
        "https://uu.pm.netease.com/v6/issues/*",
        "https://msdk.pm.netease.com/v6/issues/*"
      ],
      "js": [
        "extensions_issue_page.js"
      ],
      "run_at": "document_start"
    },
  ]
}
bash 复制代码
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-XnQUOdrKm+cYqdkT/ljnkhjaYaitt2Xh3uRQxH/M9z0='), or a nonce ('nonce-...') is required to enable inline execution.

报错比较清晰,就是注入的代码和原有代码不在一个域下,无法操作/注入javascript对象。

最后我是这样做的:

我的方法一

从其他页面获取这个数据,在url参数中携带这个信息;

我的方法二

从dom节点中获取第一个元素信息,然后通过网络请求,重新请求需要的数据。

相关推荐
青衫烟雨5 小时前
服务器上跑 Chrome 三年:Xvfb 那几个坑,和一条等待规则
chrome·浏览器·自动化运维
MyBili7 小时前
Chrome内置AI功能全攻略:Gemini侧边栏与端侧AI接口
人工智能·chrome·谷歌浏览器·隐私保护·ai助手·gemini·内置ai
MyBili1 天前
Chrome无障碍功能使用指南
chrome·实时字幕·无障碍功能·辅助功能·屏幕朗读·视觉辅助·高对比度
MyBili2 天前
Chrome站点权限精细管理指南
chrome·谷歌浏览器·权限管理·隐私安全·站点设置·通知权限管理·摄像头权限
BruceVan3 天前
别再截图贴报错了,让 AI 自己打开 Chrome 查 bug
chrome·ai编程·mcp
ZYH_06013 天前
Shell 第一阶段笔记:变量、引号与变量截取
前端·chrome·笔记
Frag0ut3 天前
Chrome 2026深色模式与护眼显示全攻略:长时间浏览舒适体验实战进阶指南
chrome·深色模式·蓝光过滤·浏览器护眼设置·深色网页适配·字体渲染优化·长时间浏览护眼
threerocks4 天前
我把「双语刷 X + 深度 AI 改写 + 去 AI 味过朱雀」做进了浏览器和终端:X Polyglot 正式上架 Chrome 商店
chrome
小宋10214 天前
Chrome 的 AI 功能在后台偷跑流量:把端侧模型做成可版本化的分发制品,用下载资格门控、差分更新与「下载未使用率」验收
大数据·人工智能·chrome
MyBili4 天前
Chrome任务管理器深度使用指南
chrome·进程管理·性能调优·任务管理器·进程排查·卡顿定位·内存泄漏排查