1

I know how to set the CSS property of an element from a Chrome JavaScript snippet (brightness in this case):

chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    chrome.tabs.executeScript(
      tabs[0].id,
      {code: 'document.getElementById("element-id").style.filter = "brightness(' + brightness_level + ')";'});
  });

But how would I retrieve the same value after that?

Trevor Reid
  • 3,310
  • 4
  • 27
  • 46

2 Answers2

0

executeScript returns the last evaluated result of the code into the callback, see documentation.

Note, when running in the active tab there's no need for chrome.tabs.query. You can simply omit the tab id (this is what "optional" means in the documentation) and the entire code will be:

chrome.tabs.executeScript({
  code: 'document.getElementById("element-id").style.filter',
}, results => {
  if (!chrome.runtime.lastError) {
    const mainPageResult = results[0];
    console.log(mainPageResult);
    // do something with mainPageResult here inside the callback
  }
}

It can't transfer DOM elements, Map, Set, ArrayBuffer, classes, functions, and so on - it can only transfer JSON-compatible simple objects and types. So, you'll need to manually extract the required data and pass it as a simple array or object.

The callback is invoked asynchronously so these topics might be useful:

Trevor Reid
  • 3,310
  • 4
  • 27
  • 46
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
-1

I'm assuming you are working from a background script so far. In order to do so you'll need a content script to run on the page containing the DOM you mentioned. In that script you will want to send a message passing the CSS value (or whatever else you want, really) as the message payload to the background script to process further.

It's going to take some time to get used to the concept by the way (at least from my own experience).

Adi H
  • 668
  • 7
  • 9
  • 1
    executeScript is running the code as a content script so the OP doesn't have problems with this part. – wOxxOm Apr 13 '20 at 03:38
  • I said I was "assuming" and unless the OP told you directly you also operated solely on assumption when you downvoted. – Adi H Apr 13 '20 at 03:50
  • This is described in the [documentation of the content scripts](https://developer.chrome.com/extensions/content_scripts#functionality). If you want to provide an alternative solution based on a content script declared via manifest.json then modify your answer accordingly to indicate it's an alternative solution, and describe how it is different, what are the benefits or pitfalls. – wOxxOm Apr 13 '20 at 03:54