Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

The popup loads fine however the CSS cannot be injected.

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

It would be of great help if someone figures what's wrong.

like image 588
stupidosaur Avatar asked Oct 21 '22 09:10

stupidosaur


1 Answers

Use chrome.tabs.insertCSS instead, as simple as that. Note that the tab id is optional:

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. 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.

like image 91
Xan Avatar answered Oct 23 '22 00:10

Xan