user2755352
user2755352

Reputation: 27

Global variable in chrome extension's content.js

Is there a way to have a global variable inside one content.js? Currently, this is my code, but it gives me 'undefined'...

window.addEventListener("message", function(event) {
  // We only accept messages from ourselves
  if (event.source != window)
      return;

  if (event.data.type && (event.data.type == "FROM_PAGE")) {
    url = event.data.text;
    window.username = event.data.subject;
    window.password = event.data.end;
    alert(window.username);
    alert(window.password);
    chrome.extension.sendRequest({redirect: url});
  }
}, false);

function get_passwords() { 
    var node_list = document.getElementsByTagName('input');
    console.log(node_list);
    var textboxes = [];
    for (var i = 0; i < node_list.length; i++) {
        var node = node_list[i];
        console.log(node);
        if (node.getAttribute('type') == 'password') {
            textboxes.push(node);
        }
    } 
    textboxes[0].value = window.password;
}

Upvotes: 1

Views: 3453

Answers (1)

aclave1
aclave1

Reputation: 1711

For a chrome extension content script, use this code in

your content script:

chrome.runtime.onMessage.addListener(function(msg,sender){

  //msg is the message, sender is where it came from

});

and in your background page:

chrome.tabs.sendMessage(tabToSendMessageTo.id, {
     message: {"greeting":"Hello World!"}
});

Here's a link to the google documentation for message passing. Message Passing

Upvotes: 1

Related Questions