簡體   English   中英

從帶有 chrome 擴展 v3 的內容腳本中注入 javascript

[英]Inject javascript from content script with a chrome extension v3

我正在將我的擴展從 V2 遷移到 V3。 現在一切正常,除了一件事。 在我的 V2 版本中,我做了

const actualCode = '(' + function () { 'console.log("demo");' } + `)();`;
const script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.remove();

請注意, console.log("demo")是對我需要注入的內容的簡化:)

我需要注入一些 javascript 以使我的 chrome-extension-magic 發生。

現在,在 V3 中,這不再起作用了。 我的 devtools-console 中出現以下錯誤

content.js:23114 
    
   Refused to execute inline script because it violates the following 
   ContentSecurity Policy directive: "script-src 'self'". Either the 
   'unsafe-inline' keyword, a hash ('sha256-tN52+5...6d2I/Szq8='), or a nonce
   ('nonce-...') is required to enable inline execution.

在遷移指南中,我注意到了這個部分

"content_security_policy": {
   "extension_pages": "...",
   "sandbox": "..."
}

但是那里沒有太多描述,所以這對我來說很神奇。 所以我希望有人知道可以幫助我嗎?

請參閱使用內容腳本訪問頁面上下文變量和函數

由於content scripts是在“孤立的世界”環境中執行的,所以我們不能在 content_script js 中做一些特殊的dom操作。

此示例將向您展示如何在文檔開始之前將 inject.js 注入web頁面:

// document_start.js
var s = document.createElement('script');
s.src = chrome.runtime.getURL('inject.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

manifest.json ManifestV3 示例

"content_scripts": [
      {
            "matches": ["<all_urls>"],
            "js": ["document_start.js"],
            "run_at": "document_start" //default document end
      }
]
"web_accessible_resources": [{
  "resources": ["inject.js"],
  "matches": ["<all_urls>"]
}]

我嘗試了相同的代碼,但是當我調用 appendChild(s) 時,它拋出異常“拒絕執行內聯腳本,因為它違反了以下內容安全策略指令 script-src'self''unsafe-eval'。unsafe-inline 關鍵字,需要 hash 或隨機數來啟用內聯執行。” 即使添加“不安全內聯”也不能解決問題。

誰能指導我如何為 Chrome V3 注入 javascript。 使用 V2,我正在使用 appendchild,它工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM