Search code examples
javascriptgoogle-chromegoogle-chrome-extensionbrowserchromium

No source code or file specified. when trying to inject CSS with chrome extension


So, this is my first chrome extension, and it will inject my CSS into the page perfectly multiple times but fails at a random time and refuses to do it again. I have no idea how this happens

This is my JS running in the background

  var style = {};
  style["file"] = "smaller.css";
  style["runAt"] = "document_start";



chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (!tab.url.startsWith("http")) return;
  let url = extractDomain(tab.url);
  chrome.storage.local.get([url, "extension_enabled"], r => {
    if (r[url] == null) return;
    if (r[url] && r["extension_enabled"])
      chrome.tabs.insertCSS(tabId, style, _ => {
        let e = chrome.runtime.lastError;
        if (e !== undefined) {
          console.log(tabId, _, e);
          console.log(e.getMessage);
        }
      });
  })
});

I'm checking the URL in the storage because I only want to inject the CSS into pages of a specific service which is distributed over multiple domains.

r[url] and r["extension_enabled"] are booleans if set.

This is the Error thrown:

{ "message": "No source code or file specified." }

I tried this extension on multiple Browsers (Google Chrome, Chromium, Opera GX) and on multiple machines. Error happens on every browser and machine but not at the same time, they all happen at a random time could be 2 Clicks or 2 Days

Maybe someone could help me resolve this issue


Solution

  • I changed my code to this:

    chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
      if (!tab.url.startsWith("http")) return;
      let url = extractDomain(tab.url);
      chrome.storage.local.get([url, "extension_enabled"], r => {
        if (r[url] == null) return;
        if (r[url] && r["extension_enabled"]){
          let style = {};
          style["file"] = "smaller.css";
          style["runAt"] = "document_start";
          chrome.tabs.insertCSS(tabId, style, _ => {
            let e = chrome.runtime.lastError;
            if (e !== undefined) {
              console.log(tabId, _, e);
              console.log(e.getMessage);
            }
            }
          });
      })
    });
    

    and defined style locally instead globally