views:

302

answers:

1

I am writing my first chrome extension, and I want to pass a variable to the currently opened tab and manipulate the DOM with it.

My extension has a button, and when clicked, is executing this code:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.executeScript(tab.id, {
  file: 'tabscript.js'
 });
});

This works fine, but I see no way to pass a variable to tabscript.js so it can be used on the opened tab.

+1  A: 

What do you need to pass a variable in to? Do you have a function you are calling in your script?

It must be noted that you don't have access to the pages Javascript, just the DOM.

If you have a particular function that you have to call with specific parameters then you should investigate content scripts and message passing.

Content scripts can get run on every page load (or a selection of pages), and you would use message passing to send a message from your extension button to the function in the content script.

Alternativly, and closer to your original idea you can construct the function you want to call at run time using the following:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.executeScript(tab.id, {
  code: 'function(){ ...... your code built dynamically ......}'
 });
});
Kinlan