简体   繁体   English

无法通过Chrome扩展程序注入CSS

[英]Cannot Inject CSS through Chrome Extension

I am trying to create a Chrome Extension that would inject CSS on to the page when the Extension button is clicked. 我正在尝试创建一个Chrome扩展程序,在单击“扩展”按钮时会将CSS注入页面。

The popup loads fine however the CSS cannot be injected. 弹出窗口加载正常但CSS无法注入。

Manifest.json: 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 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 style.css文件

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

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

tester.js: tester.js:

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

It would be of great help if someone figures what's wrong. 如果有人知道什么是错的,那将是很有帮助的。

Use chrome.tabs.insertCSS instead, as simple as that. 请改用chrome.tabs.insertCSS ,就这么简单。 Note that the tab id is optional: 请注意,选项卡ID是可选的:

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

Oh. 哦。 Also, you need to use either a popup or a listener to chrome.browserAction.onClicked . 此外,您需要使用chrome.browserAction.onClicked的弹出窗口或侦听chrome.browserAction.onClicked You can't use both, as the event is not fired while a popup is defined. 您不能同时使用两者,因为在定义弹出窗口时不会触发事件。

Two possible solutions: 两种可能的解决方

  1. Your code should instead go into background: 您的代码应该转到后台:

     { "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. Or, you just call the code when popup appears: 或者,您只需在弹出窗口时调用代码:

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

Of note: your permissions are a bit excessive for the task. 值得注意的是:您的权限对于任务而言有点过分。 Look into activeTab permission , and also note that <all_urls> permission includes file:/// URLs. 查看activeTab权限 ,并注意<all_urls>权限包括file:/// URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM