0

I'm building a Chrome extension. I have this function which is triggered as a callback for the context menu click:

background.js

function setTranslation(info, tab) {
    var parseWord = 'var word = ' + info.selectionText;
    alert(parseWord); // works here
    chrome.tabs.executeScript(tab.id, {
        code: parseWord 
    }, function () {
        chrome.tabs.executeScript(tab.id, {
            file: 'lightbox.js'
        });
    });

The lightbox.js for now only alerts the passed value:

lightbox.js

alert(word);

I'm trying to find a way to pass the value of the selection (info.selectionText) to content script (lightbox.js). It works when the value of code property in background.js is a simple string. But when I concatenate it with the value of info.selectionText it alerts undefined.

Is this because of asynchrony of the action? Is there a way to make it work with a tweak or do I have to use message passing?

Makyen
  • 31,849
  • 12
  • 86
  • 121
Sebastian
  • 1,225
  • 1
  • 16
  • 27

1 Answers1

1

Assuming info.selectionText is abc, look at the injected code: var word = abc. Now as you can see abc here is not a string, but a variable name that's not defined!

The robust solution is to use JSON.stringify that escapes embedded quotes and adds doublequotes around the string:

var parseWord = 'var word = ' + JSON.stringify(info.selectionText);
wOxxOm
  • 65,848
  • 11
  • 132
  • 136