【问题标题】:Cannot Inject CSS through Chrome Extension无法通过 Chrome 扩展程序注入 CSS
【发布时间】:2014-04-23 17:08:16
【问题描述】:

我正在尝试创建一个 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"});
});

如果有人弄清楚出了什么问题,那将是非常有帮助的。

【问题讨论】:

    标签: javascript css google-chrome-extension


    【解决方案1】:

    改用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"});
      

    注意:您的权限对于该任务来说有点过分。查看activeTab permission,还要注意&lt;all_urls&gt; 权限包括file:/// URL。

    【讨论】:

      猜你喜欢
      • 2011-11-28
      • 2012-02-25
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2016-06-16
      • 2021-03-05
      相关资源
      最近更新 更多