35

This function has a callback like function(array of any result) {...};

But I don't know what is the result means.

For example,

chrome.tabs..executeScript(null,
   {code:"var x = 10"},
   function(){});

how to return the x to the callback?

kynan
  • 13,235
  • 6
  • 79
  • 81
dusthand
  • 353
  • 1
  • 3
  • 4
  • Look at [this question in Google Groups](https://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/chromium-extensions/Nco_o24bZ9A). – Stan Oct 31 '12 at 21:06

1 Answers1

58

The result of a script is the last expression being evaluated. So in your example you could use:

chrome.tabs.executeScript( null, {code:"var x = 10; x"},
   function(results){ console.log(results); } );

This will log [10] to the extension's console.

results is actually an array of values because if the page has more than one frame you can specify that the script should be injected in each one of them and get the result of all injections. See the specification for executeScript. If you don't specify allFrames: true, then results will always be a single element array.

rsanchez
  • 14,467
  • 1
  • 35
  • 46
  • 1
    I have this `chrome.tabs.executeScript( null, {code:"var x = 10; x"}, function(results){ alert(results); } );` but gets undefined as an alert. Do you have any clue why this might happen? – WSBT Jul 16 '13 at 16:36
  • 2
    @user1032613 that will happen if your extension doesn't have permissions to execute a script on the current tab. Make sure the domain is included in the `permissions` setting of your `manifest.json` – rsanchez Jul 16 '13 at 16:46
  • 1
    Thanks! And I just realized that, modifications made to manifest.json will only take effect after I reinstall the extension. – WSBT Jul 16 '13 at 16:54
  • @user1032613 You can reload the extension by turning on the developer mode in chrome://extensions. or press ctrl-R – iankit Dec 19 '14 at 18:11
  • For me, the alert immediately disappears? – PascalVKooten Mar 10 '17 at 19:32
  • 2
    Note that the result will too be null if the code throws an error. – Pacerier Aug 06 '17 at 03:14
  • @virus No. You must be very careful with the code to be executed, if you want the results. Use `try..catch` and always return a `structured clonable` type (a string will do, an error won't) – manuell Sep 04 '18 at 12:59