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节点中获取第一个元素信息,然后通过网络请求,重新请求需要的数据。

相关推荐
qetfw14 小时前
Bash 字符串处理:参数展开、序列与脚本执行方式
linux·开发语言·chrome·bash
白日做梦Q21 小时前
Chrome商店访问不了,无法现在安装插件?利用Edge商店迁移扩展完整实操教程问题背景
前端·chrome·edge
其实防守也摸鱼1 天前
Cylab在线靶场——挑战图书馆初学者指南
服务器·前端·数据库·chrome·安全·网络安全·靶场
志尊宝2 天前
AI原生前端开发(011):Chrome 148+内置Gemini Nano入门
前端·chrome·ai-native
Frag0ut2 天前
Chrome媒体与通信中枢:2026年音视频处理及跨端协作原生指南
chrome·谷歌浏览器·画中画·媒体处理·音视频转换·webrtc诊断·跨设备传输
我喜欢就喜欢2 天前
Chrome 插件开发实战指南
前端·chrome
死磕音视频2 天前
Gemini in Chrome 入门:让浏览器里的 AI 读懂当前网页
chrome·gemini·ai浏览器·网页总结
兮动人3 天前
Chrome 152 升级后本地请求全挂了?是 LNA 策略在搞事
前端·chrome·lna·local network
Frag0ut5 天前
Chrome最新版不再支持Win7?解决方案与原因解析
chrome·谷歌浏览器·windows7·supermium·firefox esr·chrome 109
前程6195 天前
我用 Chrome 插件把小红书的灵感收集做成了有字段的工作流
chrome