Exploring the concept of importing with chrome.tabs.insertCSS()

chrome.tabs.insertCSS(tabId, { code : '@import url("custom.css");' });

OR

chrome.tabs.insertCSS(tabId, { file : 'importer.css' });

importer.css:

@import url("custom.css");
a { color:red!important; } /* this rule applied successfully though. */

Seems like there is an issue with getting the CSS to work as intended.

Any ideas on why it's not functioning properly and how to troubleshoot it?

Edit:

I might be searching in the wrong place for clues, but as per the source code, it suggests that the injected CSS is parsed using the regular style sheet parser. In theory, if the @import directive works in standard CSS documents, it should function the same way in injected CSS.

Refer here for more information on script injection

void ScriptInjection::InjectCss(blink::WebLocalFrame* frame) {
  std::vector<std::string> css_sources =
      injector_->GetCssSources(run_location_);
  for (std::vector<std::string>::const_iterator iter = css_sources.begin();
       iter != css_sources.end();
       ++iter) {
    frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter));
  }
}

Edit:

Here is a piece of sample code that seems to be encountering issues:

Directory structure:

ext.root
|-- custom.css
|-- custom.css.js
|-- importer.css
|-- manifest.json

manifest.json:

{
   "background": {
      "scripts": [ "custom.css.js" ],
      "persistent": true
    },
   "manifest_version": 2,
   "name": "custom.css",
   "version": "1.0",
   "web_accessible_resources" : [ "*" ],
   "permissions" : [ "webNavigation", "http://*/", "https://*/" ]
}

custom.css.js:

chrome.webNavigation.onCommitted.addListener(function(details) {

    console.log('inserting css');
    console.log(chrome.runtime.getURL("custom.css"));

    chrome.tabs.insertCSS(details.tabId, { file : 'importer.css' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import url("custom.css");' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import url(custom.css);' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import url("' + chrome.runtime.getURL("custom.css") + '");' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import url(' + chrome.runtime.getURL("custom.css") + ');' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import "custom.css";' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import custom.css;' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import "' + chrome.runtime.getURL("custom.css") + '";' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import ' + chrome.runtime.getURL("custom.css") + ';' });
});

importer.css:

@import "custom.css";
@import "chrome-extension://__MSG_@@extension_id__/custom.css";

@import custom.css;
@import chrome-extension://__MSG_@@extension_id__/custom.css;

@import url("custom.css");
@import url("chrome-extension://__MSG_@@extension_id__/custom.css");

@import url(custom.css);
@import url(chrome-extension://__MSG_@@extension_id__/custom.css);

body { background-color: red!important; } /* change page background color to red */

custom.css (Rules in this file are supposed to be applied but not):

body { border: 20px solid red!important; } /* add a 20px border around the body. */
a { background-color: blue!important; } /* change all link's background color to blue. */

Answer №1

When attempting to inject a file into a tab, keep in mind that relative URLs will follow its origin.
For example, if you're injecting into

http://example.com/test/index.html
, the CSS will look for
http://example.com/test/custom.css
.

If custom.css is within the extension, use the absolute path from chrome.runtime.getURL():

chrome.tabs.insertCSS(
  tabId, 
  { code : '@import url("' + chrome.runtime.getURL(custom.css) + '");' }
);

You can also try using the special constant @@extension_id:

@import url("chrome-extension://__MSG_@@extension_id__/custom.css");

Although not guaranteed, it may work.

Lastly, ensure that the imported CSS file is listed in web_accessible_resources.

Answer №2

The use of @important in conjunction with tabs.insertCSS() does not function as expected. It appears that the insertCSS method is being processed before injection into the page, and the exact specifications on how this processing occurs are not clearly documented. Specifically, the use of !important also does not have the desired effect in this context.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Move a button using jQueryUI

HTML code resides below <!doctype html> <html> <head> <title>jQuery UI: Alphabet Matcher</title> <link href="css/normalize.css" rel="stylesheet"> <link href="matchalphabate.css" rel="styl ...

Android layout featuring Ionic2 navbar with icons aligned on both sides at the top

<ion-header> <ion-navbar align-title="center" color="primary" hideBackButton> <ion-buttons ion-button icon-only start class="card-buttons"> <button class="card-buttons" (t ...

positioning of content on the left, right, and center

My task involves using CSS to adjust the positions of various elements on a webpage. Currently, the right position navigation bar and the liquid layout are working fine, but the positioning of the "content" and "right navigation bar" is not correct. I ai ...

Trouble Viewing Image File

I am facing an issue where I cannot upload an image file from my computer onto my HTML file, as it is not showing up in the browser. However, when I link an image file from the web, it works perfectly fine. I have double-checked the file path and ensured ...

Is there a way to create a dynamic CSS for a custom JSF component through code generation?

I am currently developing a custom JSF component that displays content in multiple columns in a "responsive" manner. This component utilizes the "CSS Multi-column Layout Module" (http://www.w3.org/TR/css3-multicol/) (tutorial available in French: ). Belo ...

Triggering the function once the text field is tapped again

I recently integrated a JavaScript scroll framework to create a stylish scrollbar for windows. I simply added it to a div: this.displayDiv = function () { $("#myDiv").niceScroll(); } <a href="#" onclick="manager.displayDiv();"> It ...

Align the bottom borders to the lowest content on each line

I am working on designing my homepage using HTML, CSS, JSP, and JavaScript, focusing on the sale of musical instruments and facilitating communication among users. Right now, I am in the process of creating a site-map for my menu configuration chart using ...

Ever-changing CSS class attribute?

One challenge I'm facing involves a navigation bar with elements rendered using the Struts2 iterator tag. Here is an example: <ul> <li><a href="#">Home</a></li> <s:iterator var="row" value="#session.PrivMenu.chil ...

Struggling to make css selector acknowledge the margins on the right and left

I am trying to style two inner divs within a containing div by floating the first one to the left and the second one to the right. Additionally, I want to add a margin of 15px on the left for the first div and on the right for the second div. The challenge ...

What is the method for setting a cell's row-span to 2 using bootstrap?

Is there a way to make the red cell in a Bootstrap grid have a row-span=2 and fill the second row as well? .cell {height: 100px; border: 1px solid; border-collapse:collapse;} .red {background: red;} .yel {background: lightyellow;} <link href="https:/ ...

Incorporating orientation settings within a media query using MUI

In my current project, I am utilizing MUI in conjunction with React. To specifically style the iPad resolution using MUI breakpoints, I have implemented the following code snippet: contentBox:{ width:"10%", paddingLeft:"10p ...

There are certain CSS3 properties that are not being accounted for in the CSS min

I've incorporated several newer CSS3 properties in my stylesheet, but I'm concerned that the minification tool I'm currently utilizing may not be capturing all of these properties: .big-blue-button:hover { text-decoration: none; bac ...

Ways to eliminate the vertical scroll feature in a kendo chart

I am encountering an issue while loading a kendo chart inside grid-stack.js where I am unable to resize the height properly. Whenever I decrease the height, a vertical scroll appears which should not happen. I have tried setting the height to auto and refr ...

One simple fix for removing default focus styles across all browsers

Is there a universal method to disable the default styling of focused elements across all browsers? If not, what are some of the common styles implemented by the most popular browsers? ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

Text off-center in Bootstrap Badge

I'm struggling to find a way to center my text with the icon properly. This issue is only happening in Google Chrome. You can view the problem in action on this code snippet. @import url('https://fonts.googleapis.com/icon?family=Material+Icons ...

The bootstrap navbar dropdown feature isn't functioning properly on iPhones

Currently utilizing "bootstrap": "~3.3.4" within the mean.js framework, I am facing an issue with the navbar dropdown menu. On desktop, everything functions as expected - the dropdown opens and remains open when the icon is clicked. However, once deployed ...

Concealing the Footer on Mobile Websites in Muse UI When the Keyboard Appears

In this project, I am using vue.js along with muse.ui and only incorporating JavaScript and CSS without the jQuery library. Currently, the footer position always ends up on top of the keyboard whenever an input field is focused. Is there a way to ensure th ...

Struggling with adding two-digit numbers in a JavaScript calculator

While I can add single digits with no problem, adding double digits proves to be a bit tricky. The split method in this if statement is useful for isolating individual numbers, but it struggles when dealing with double digit numbers. if(e.value == '= ...

Repeater containing a speech bubble

The image above shows the rendered CSS after changing the background color of .speech_bubble_content to red. However, the speech bubble is not displaying correctly. I am using the code below to fetch data from a database and bind it to a repeater. I have ...