0

I'm currently working on a Chrome extension but I got stuck.. I'm trying to manipulate a textarea with the Chrome extension. If I put in a value directly, the code works fine, but if I want to get the value from a variable it won't work..

This code WORKS:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript({
    code: 'document.getElementById("message").value = "Hello!";'
  });
});

This code DOESN'T WORK:

carName = "Volvo";
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript({
    code: 'document.getElementById("message").value = carName;'
  });
});

Can someone tell me what's wrong and how I should do it right?

Thanks in advance

2 Answers 2

1

This is because that code is executed in the context of the page where carName isn't defined. Instead of including the var name in the string, append the var value to the string like so:

carName = "Volvo";
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript({
    code: 'document.getElementById("message").value = '+carName+';'
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Also tried that, but it didn't work.. I think it has something to do with the executeScript function, is there a way to avoid that?
0

What about defining the variable inside the listener:

chrome.browserAction.onClicked.addListener(function(tab) {
  carName = "Volvo";
  chrome.tabs.executeScript({
    code: 'document.getElementById("message").value = carName;'
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.