1
var stuff = "Heeeey";   
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
    file: 'sendMessage.js'
});;

How can I pass the variable stuff to the file, sendMessage.js?

Dgameman1
  • 378
  • 5
  • 24

1 Answers1

0

There is no way to pass a variable into the executed script. This is done I guess for security and performance reasons because this may introduce memory leaks.

What you can do is passing a value of the variable.

There are two ways:

  1. Send the message to your script, see the messaging for communication between extension and pages
  2. Inject the variable value into the page script using the same executeScript but passing the script as a string instead of the file name. You can do executeScript calls: one for value injections and another for file injection.
smnbbrv
  • 23,502
  • 9
  • 78
  • 109
  • Not sure if I got it to work. I'm attempting to follow #1. `chrome.runtime.onMessage.addListener(function(message) { if (message.type == "pickLine") { pickLineText = message.content; } });` Is in my sendMessage.js and no matter what, the pickLine seems to always be blank – Dgameman1 Apr 29 '16 at 07:33
  • @ILovephp123 this is an asynchronous message, maybe you send it before the listener is registered on the page? Also you need to add all required permissions, last time I tried to do a similar thing I spent quite some time to make it work, it is not that obvious how they do it in chrome... – smnbbrv Apr 29 '16 at 07:42
  • Does the sendMessage go above or below the execute shell? – Dgameman1 Apr 29 '16 at 07:51
  • I think there is no difference as long as both operations are asynchronous. I think you might need to wait for some milliseconds on the page to get the value and this is ugly. Most likely the second option is way more comfortable for simply setting the value – smnbbrv Apr 29 '16 at 07:56
  • I feel like the second option you provided is a lot easier, I just don't really understand what you're saying lol. Sorry =/ – Dgameman1 Apr 29 '16 at 07:57
  • ehm you still don't? :) should I explain more on the second option? – smnbbrv Apr 29 '16 at 07:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/110610/discussion-between-ilovephp123-and-smnbbrv). – Dgameman1 Apr 29 '16 at 08:02