Chrome 扩展程序 - 如何在清单版本 3 (MV3) 中获取窗口对象?

问题描述

概述

我能够通过新的 chrome.scripting API 成功注入我的 Javascript 脚本。

但是,我仍然无法通过这个注入的脚本访问页面window 对象。

我的尝试

回到 MV2,我曾经做过以下事情:

async function getwindow() {
    return new Promise(function (resolve,reject) {
      const script = document.createElement('script');
      script.text = `
            const _window = JSON.stringify(window);
            document.body.insertAdjacentHTML("beforebegin","<div id='dummy' style='display:none;width:0;height:0;pointer-events:none;'>"+_window+"</div>")
        `;

      document.getElementsByTagName('head')[0].appendChild(script);

      const _window = document.getElementById('dummy');
      const data = JSON.parse(_window.innerText)

      script.remove();
      resolve(data);
    });
  }

 (async () => {
    const _window = await getwindow();
    console.log(_window)
  })();

但这已经不可能了。它给了我以下错误

拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src 'self'”。启用内联执行需要“unsafe-inline”关键字、哈希(“sha256-iAKY8pCLpBsspttuizEMbuFVrucrXcGUoo/RYdGQEyw=')或随机数(“nonce-...”)。

基于该错误,我找到了 this answerthis question 答案,但它没有解决我的问题,因为前者用于 MV2,而后者使用的是外部脚本。我无法使用本地脚本使其工作。

我想要达到的目标

我想从我的 Chrome 扩展程序访问给定网站的 window 对象。

其他注意事项

  • 在我的清单中,我拥有以下权限:
  "permissions": ["scripting","activeTab","webRequest"]

此外,我在 content_scriptsweb_accessible_resources添加了我的脚本。

非常感谢任何帮助。

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)