简体   繁体   中英

Injecting CSS attributes as javascript in a Chrome Extension without overriding the previous ones

So I'm trying to execute the following lines of code in a chrome extension:

  chrome.tabs.executeScript({
    code: 'var elements = document.getElementsByTagName("*"); for (var i=0; i < elements.length; i++) { elements[i].setAttribute("style", "font-family: Courier !important");}'
  });
  chrome.tabs.executeScript({
    code: 'var elements = document.getElementsByTagName("*"); for (var i=0; i < elements.length; i++) { elements[i].setAttribute("style", "font-size: 18pt !important");}'
  });
  chrome.tabs.executeScript({
    code: 'var elements = document.getElementsByTagName("*"); for (var i=0; i < elements.length; i++) { elements[i].setAttribute("style", "backgrond-color: #fbfbfb !important");}'
  });
  chrome.tabs.executeScript({
    code: 'var elements = document.getElementsByTagName("*"); for (var i=0; i < elements.length; i++) { elements[i].setAttribute("style", "line-height: 1.5 !important");}'
  });

The problem is, each line will override the last line's CSS changes. I could fix this by putting all of the CSS changes in one line. However, I'd like to make each line work based on the status of a variable. For example:

if (var_a === "true") {
  chrome.tabs.executeScript({
    code: 'var elements = document.getElementsByTagName("*"); for (var i=0; i < elements.length; i++) { elements[i].setAttribute("style", "font-family: Courier !important");}'
  });
}
if (var_b === "true) {
  chrome.tabs.executeScript({
    code: 'var elements = document.getElementsByTagName("*"); for (var i=0; i < elements.length; i++) { elements[i].setAttribute("style", "font-size: 18pt !important");}'
  });
}

How would I do this?

Collect the style changes in one place before applying them.

var style = "";
if (var_a === "true") style += "font-family: Courier !important;";
if (var_b === "true") style += "font-size: 18pt !important;";
/* ... */
chrome.tabs.executeScript({
  code:
    'var elements = document.getElementsByTagName("*");' +
    'for (var i=0; i < elements.length; i++) {' + 
      'elements[i].setAttribute("style", "' + style + '");' +
    '}'
});

Alternatively, you can manipulate the .style property instead of the attribute directly. eg:

elements[i].style.setProperty("font-family", "Courier", "important");

to manipulate rules one by one without overwriting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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