我可以使用内容脚本 js 文件以编程方式注入 CSS 文件吗?

发布于 2025-01-06 18:06:43 字数 1962 浏览 1 评论 0原文

我可以使用内容脚本 js 文件以编程方式注入 CSS 文件吗?

当 js 文件链接到我的 popup.html 时,我可以注入 css。问题是我必须单击按钮打开弹出窗口才能注入 css。我希望它在后台自动发生。

我的代码中发生了什么...

  1. 通过 XMLHttpRequest 从 MySQL 数据库获取变量
  2. 调用函数“processdata()”
  3. “processdata” 将处理来自 XMLHttpRequest 的数据。更具体地说,拆分变量,将其放入 2 个不同的变量并使它们成为全局变量
  4. 我调用函数“click()”
  5. “click”然后将使用 setTimeout 在 1250 毫秒后设置 css
  6. 我使用 chrome.tabs.insertCSS 插入CSS。 css 名称是变量“currenttheme”,

正如我之前提到的,它确实可以使用弹出窗口。但必须在注入 CSS 之前打开弹出窗口。

如何让这一切自动发生,无需任何用户交互

这是我的代码:

    function getData() {
if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        user_data = xmlhttp.responseText;
        window.user_data = user_data;
        processdata();
        }
      }
    xmlhttp.open("GET","http://localhost:8888/g_dta.php",true);
    xmlhttp.send();
}

getData();

function processdata() {
  var downdata = user_data.split('|||||');
  var installedthemes = downdata[0];
  var currenttheme = downdata[1].toString();
  window.currenttheme = currenttheme;
  click();
  }

function click(e) { 
      function setCSS() {
          chrome.tabs.insertCSS(null, {file:currenttheme + ".css"});
          }
      setTimeout(function(){setCSS()}, 1250);
      document.getElementById('iFrameLocation').innerHTML = "<iframe src='http://localhost:8888/wr_dta.php?newid="+e.target.id+"'></iframe>";
      getData();
}

document.addEventListener('DOMContentLoaded', function () {
  var divs = document.querySelectorAll('div');
  for (var i = 0; i < divs.length; i++) {
    divs[i].addEventListener('click', click);
  }
});

Can I inject a CSS file programmatically using a content script js file?

It is possible for me to inject the css when the js file is linked to my popup.html. The problem is I have to click on the button to open the popup to inject the css. I want it to happen automatically and in the background.

What happens in my code...

  1. Get a variable from a MySQL database through a XMLHttpRequest
  2. Call the function, "processdata()"
  3. "processdata" Will process the data from the XMLHttpRequest. More specifically, split the variable, put it into 2 different variables and make them global
  4. I call the function, "click()"
  5. "click" Then will set the css after 1250 milliseconds using setTimeout
  6. I use chrome.tabs.insertCSS to insert the css. The css name is the variable, "currenttheme"

As I mentioned before it does work using the popup. But the popup has to be opened before the CSS gets injected.

How do I make this all happen automatically, without any user interaction?

Here is my code:

    function getData() {
if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        user_data = xmlhttp.responseText;
        window.user_data = user_data;
        processdata();
        }
      }
    xmlhttp.open("GET","http://localhost:8888/g_dta.php",true);
    xmlhttp.send();
}

getData();

function processdata() {
  var downdata = user_data.split('|||||');
  var installedthemes = downdata[0];
  var currenttheme = downdata[1].toString();
  window.currenttheme = currenttheme;
  click();
  }

function click(e) { 
      function setCSS() {
          chrome.tabs.insertCSS(null, {file:currenttheme + ".css"});
          }
      setTimeout(function(){setCSS()}, 1250);
      document.getElementById('iFrameLocation').innerHTML = "<iframe src='http://localhost:8888/wr_dta.php?newid="+e.target.id+"'></iframe>";
      getData();
}

document.addEventListener('DOMContentLoaded', function () {
  var divs = document.querySelectorAll('div');
  for (var i = 0; i < divs.length; i++) {
    divs[i].addEventListener('click', click);
  }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

把昨日还给我 2025-01-13 18:06:43

您可以通过编程方式创建一个新的 标记并将其添加到 部分,就像动态加载 JS 文件一样。

var link = document.createElement("link");
link.href = "http://example.com/mystyle.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);

这是关于该主题的一篇文章

You can programmatically create a new <link> tag and add it to the <head> section just like JS files are loaded dynamically.

var link = document.createElement("link");
link.href = "http://example.com/mystyle.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);

Here's an article on the topic.

你在我安 2025-01-13 18:06:43

扩展闪烁

对生态系统的一次创伤不难修复

前言:

在将 CSS 添加到页面的多种方法中,大多数都会导致屏幕闪烁- 最初显示未应用 CSS 的页面,然后再应用它。我尝试了多种方法,以下是我的发现。

标记

您需要在 document_start 上注入内容脚本

该代码如下所示:

var link = document.createElement('link');
link.href =  chrome.runtime.getURL('main.css');
  //chrome-extension://<extension id>/main.css
link.rel = 'stylesheet';
document.documentElement.insertBefore(link);

对于某些动态 CSS 代码:

var customStyles = document.createElement('style'); 
customStyles.appendChild(document.createTextNode(
   'body { background-color: ' + localStorage.getItem('background-color') + '}'
));
document.documentElement.insertBefore(customStyles); 

document_start 上的脚本中执行此操作>确保没有闪烁!

推理

在这个 JavaScript 文件中,您可以处理任意数量的编程事物。 manifest.json 中提供的 URL 模式匹配非常有限,但在这里您实际上可以查看 a 的所有 ?query_string#hash url,并使用完整的正则表达式和字符串操作来决定是否注入CSS。该 CSS 还可以基于设置,和/或与后台页面的消息传递相协调。

结束语

  • 不要使用 .insertCSS,您会注意到闪烁。

Extension flicker

A trauma to the ecosystem that isn't hard to fix

Preface:

Among many ways to get your css added to a page, most of them cause the screen to flicker - initially showing the page without your css applied, and then later applying it. I've tried several ways, below are my findings.

The gist

You need to append a CSS <link> or a <style> tag in a Content script injected on document_start

That code looks like this:

var link = document.createElement('link');
link.href =  chrome.runtime.getURL('main.css');
  //chrome-extension://<extension id>/main.css
link.rel = 'stylesheet';
document.documentElement.insertBefore(link);

For some dynamic CSS code:

var customStyles = document.createElement('style'); 
customStyles.appendChild(document.createTextNode(
   'body { background-color: ' + localStorage.getItem('background-color') + '}'
));
document.documentElement.insertBefore(customStyles); 

Doing this in a script on document_start ensures there is no flicker!

The reasoning

In this JavaScript file you can handle any number of programmatic things. The URL pattern matching offered in manifest.json is very limited, but here you can actually look at all the ?query_string and #hash of a url, and use full regular expressions and string operations to decide whether or not to inject CSS. That CSS can also be based on settings, and/or coordinate with messaging to the background page.

Parting words

  • Don't use .insertCSS, you will notice a flicker.
任性一次 2025-01-13 18:06:43

这很简单,您可以添加到清单的权限字段:请参阅 web_accessible_resources

 , "web_accessible_resources": [
        "mystyle.css"
    ]

并将其添加到 content_scripts 中,

"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "css": ["mystyle.css"],
        "js": ["jquery-1.10.2.min.js","content.js","my.min.js"]
    }],

您还可以使用编程注入和 insertCSS()

chrome.tabs.insertCSS(integer tabId, object details, function callback)

It's to simple you could add to the manifest's permissions field : See web_accessible_resources

 , "web_accessible_resources": [
        "mystyle.css"
    ]

and also add this in content_scripts

"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "css": ["mystyle.css"],
        "js": ["jquery-1.10.2.min.js","content.js","my.min.js"]
    }],

you also add same thing using Programmatic injection and insertCSS().

chrome.tabs.insertCSS(integer tabId, object details, function callback)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文