2014-04-23 114 views
2

我試圖創建一個Chrome擴展插件,當單擊擴展按鈕時將CSS插入頁面。無法通過Chrome擴展插入CSS

彈出式加載正常,但CSS無法注入。

的manifest.json:

{ 
    "name": "Flat Firemem", 
    "version": "1.0", 
    "manifest_version": 2, 
    "description": "Arranges the page properly in the dump.", 
    "browser_action": { 
    "default_icon": "logo.png", 
    "default_popup": "popup.html" 
    }, 
    "permissions": ["tabs", "<all_urls>", "file:///*"] 
} 

popup.html

<!DOCTYPE html> 
<html style=''> 
<head> 
<script src='tester.js'></script> 
</head> 
<body style="width:400px; border: 2px solid black;background-color:LightGray;"> 
<div id='message'>Hello..!!</div> 
</body> 
</html> 

的style.css

* 
{ 
    float: none !important; 
    position: static !important; 
} 

table, tbody, td, tfoot, th, thead, tr 
{ 
    display: block !important; 
} 

tester.js:

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.executeScript(null, 
          {file:"style.css"}); 
}); 

這將是很大的幫助,如果有人數字出了什麼問題。

回答

2

改爲使用chrome.tabs.insertCSS,就這麼簡單。請注意,標籤ID是可選的:

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.insertCSS({file:"style.css"}); 
}); 

哦。此外,您需要使用彈出式窗口或偵聽器來訪問chrome.browserAction.onClicked。 您不能同時使用兩者,因爲在定義彈出窗口時事件未被觸發。

兩個可能的解決方案:

  1. 你的代碼應該不是進入背景:

    { 
        "name": "Flat Firemem", 
        "version": "1.0", 
        "manifest_version": 2, 
        "description": "Arranges the page properly in the dump.", 
        "browser_action": { 
        "default_icon": "logo.png", 
        }, 
        "background": { 
        "scripts": ["tester.js"] 
        }, 
        "permissions": ["tabs", "<all_urls>", "file:///*"] 
    } 
    
  2. 或者,你只需要調用代碼彈出窗口時:

    // tester.js: no need to listen to event 
    chrome.tabs.insertCSS({file:"style.css"}); 
    

注意:您的權限a對於任務有點過分。看看activeTab permission,還請注意,<all_urls>權限包括file:///的網址。