【问题标题】:Chrome Extension: How do I inject a script that the user provided?Chrome 扩展程序:如何注入用户提供的脚本?
【发布时间】:2022-06-15 20:26:40
【问题描述】:

我正在为 chrome 做一个扩展,用户可以在其中输入脚本,然后按“运行”将其注入当前选项卡。我正在使用 MV3(清单 v3)。有没有办法做到这一点?

我的代码:

HTML:

<div class="scriptrunner">
    <h1>Script Runner</h1>
    <textarea placeholder="Enter script here" id="script"></textarea>
    <button id="run">Run Script</button>
</div>

Javascript:

let button = document.getElementById("run");
button.addEventListener("click", async () => {
    let input = document.getElementById("script");
    let script = input.value;
    // this is where the script would be ran
});

我尝试了以下方法:

  • 使用chrome.scripting.executeScript()
  • 使用eval()
  • 使用chrome.scripting.executeScript()插入带有函数的脚本标签,然后运行函数

我刚开始研究 chrome 扩展,所以也许我错过了一些东西,或者这是不可能的。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension chrome-extension-manifest-v3


    【解决方案1】:

    执行任意用户代码(用户脚本)尚未在 ManifestV3 中实现。

    同时,我们可以在 页面上下文 中运行此类代码,即不作为内容脚本:

    async function execInPage(code) {
      const [tab] = await chrome.tabs.query({currentWindow: true, active: true});
      chrome.scripting.executeScript({
        target: {tabId: tab.id},
        func: code => {
          const el = document.createElement('script');
          el.textContent = code;
          document.documentElement.appendChild(el);
          el.remove();
        },
        args: [code],
        world: 'MAIN',
        //injectImmediately: true, // Chrome 102+
      });
    }
    
    execInPage('console.log(123)');
    

    警告!如果网站有严格的Content-Security-Policy,这可能会被网站阻止,在这种情况下,您可以通过declarativeNetRequest API 删除此标头。

    【讨论】:

    • 非常感谢!但是,此脚本仅适用于某些网站。在某些情况下,它会引发错误Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'。有没有办法解决这个问题?
    • 这意味着这些网站有一个严格的 CSP,你必须禁用或规避它,例如通过使用declarativeNetRequest 删除Content-Security-Policy 标头。
    • 我很抱歉,但是我将如何使用 declarativeNetRequest 做到这一点?它会涉及制定规则集还是我错过的其他事情?
    • 查看文档中的示例并添加删除此标头的规则。
    • 我检查了文档,并使用它所说的添加了一条规则。它仍然无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 2022-11-07
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多