change the color of a div from an external page from a plugin

3

I made an add-on for chrome, the functionality is to change the color of the div "textarea_simulator" from the page link , just for doing the test I'm playing with that div but I can not change the color, this is my code js.

    chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript({
    code: 'document.getElementById(textarea_simulator).style.backgroundColor="red"'
  });
});
//author -- rn3w

and the manifest.json file is:

{
  "name": "cambio del color",
  "description": "cambio de color",
  "version": "1.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_title": "cambiar la vista en chrome "
  },
  "manifest_version": 2
}
//author ---rn3w---

I did the test to change the color of the background I did the test with google, with this version of my code and it works.

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript({
    code: 'document.body.style.backgroundColor="blue"'
  });
});
//author -- rn3w
    
asked by hubman 28.10.2016 в 00:53
source

1 answer

3

The way you are implementing it is for when you click on the extension icon, loading a script that runs in the background and when you are in a tab that matches the URL ... a Little complicated otherwise : -)

To inject JavaScript or CSS code into a page, you should use content scripts .

This would be the basic configuration of the manifest.json :

{
    "manifest_version": 2,
    "name": "cambio del color",
    "description": "cambio de color",
    "version": "1.0",
    "author": "m3w",
    "icons": {
        "16": "images/icon16.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
    },
    "permissions": [
        "*://www.ruat.gob.bo/Principal.jsf"
    ],
    "content_scripts": [
        {
            "matches": [
                "*://www.ruat.gob.bo/Principal.jsf"
            ],
            "js": ["cambiarcolor.js"],
            "css": ["cambiarcolor.css"],
            "run_at": "document_end"
        }
    ]
}

Observe the end: we are injecting a file with JavaScript code that will run on document_end (when finish loading the DOM), and a CSS (only because I'm going to use it in the 2nd example, but you can delete it).

cambiarcolor.js

var simulator = document.getElementById('textarea_simulator');
if (simulator) {
    simulator.style.backgroundColor = 'red';
}

console.debug('Se cargó la extensión: Cambiar Color');

Simpler, is not it?


Another alternative would be without using JavaScript, directly using the CSS that we defined in the manifest.

cambiarcolor.css

#textarea_simulator {
    background-color: red;
}
    
answered by 28.10.2016 / 02:37
source