簡體   English   中英

使用Chrome擴展程序向網頁添加按鈕

[英]Add buttons to webpage with Chrome Extension

我正在嘗試構建一個Chrome擴展程序,該擴展程序將在Deezer的相冊頁面上添加一個按鈕。

我的清單如下:

{
  "manifest_version": 2,

  "name": "Deezeet",
  "description": ".",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["https://www.deezer.com/*", "http://www.deezer.com/*"],
      "js": ["jquery.js", "popup.js"],
      "run_at": "document_end"
    }
  ],
  "web_accessible_resources": ["script.js"],
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "content_security_policy": "script-src 'self' https://api.deezer.com; object-src 'self' https://api.deezer.com; script-src 'self'"
}

我的popup.js(從此處開始 ):

var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

還有我的script.js(現在僅用於測試):

$('header').hide();

但這是行不通的。 我所有的JS都在彈出窗口中運行。 我能做什么?

您正在打開一個彈出窗口,並在彈出窗口中看到效果:

[...]即使我使用alert('bam')或類似的東西,它們也都在我的彈出窗口中運行。

當您打開它時,它與任何其他頁面無關。 您已將腳本設置為內容腳本。 當您導航到頁面或刷新現有頁面時,它將執行。


如果您需要在單擊擴展按鈕時觸發腳本,則應從清單中刪除default_popup屬性,添加一個后台腳本,然后在其中添加一個單擊處理程序:

chrome.browserAction.onClicked.addListener(function(tab){
  chrome.tabs.executeScript(tab.id, {file: "popup.js"});
  // Or, alternatively, send a message to an already-injected script
});

請注意:將腳本作為<script>元素注入是一種非常笨拙的解決方案,僅需要避開孤立的上下文。 在您的測試案例中,您僅訪問頁面的DOM,並且popup.js包裝器。

暫無
暫無

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

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