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

相关推荐
守城小轩1 天前
Chromium 138 编译指南 - Android 篇:从Linux版切换到Android版(六)
android·chrome·指纹浏览器·浏览器开发·超级浏览器
守城小轩1 天前
Chromium 138 编译指南 - Android 篇:环境搭建与准备(一)
android·chrome·指纹浏览器·浏览器开发
依旧很淡定2 天前
Selenium(Python)创建Chrome浏览器实例
chrome·python·selenium
智能化咨询3 天前
玩转ClaudeCode:通过Chrome DevTools MCP实现高级调试与反反爬策略
前端·chrome·chrome devtools
TeleostNaCl3 天前
实战 | 使用 Chrome 开发者工具修改网页源码跳过前端校验
前端·chrome·经验分享·后端·js
ARTHUR-SYS3 天前
基于Kali linux 安装pyenv及简单使用方法及碰到的问题
linux·运维·chrome
blues_C4 天前
Playwright MCP vs Chrome DevTools MCP vs Chrome MCP 深度对比
前端·人工智能·chrome·ai·chrome devtools·mcp·ai web自动化测试
数智顾问4 天前
玩转ClaudeCode:通过Chrome DevTools MCP实现页面抓取和调试的基础入门
chrome
my一阁5 天前
一文解决Chrome使用
前端·chrome
高斯林.神犇5 天前
javaWeb基础
前端·chrome