NoviceCoding
NoviceCoding

Reputation: 6361

Chrome Extension Message Passing - Code included

I have a contentscript called file.js that creates variable "found". I want to send the values of varibale "found" to a textbox in popup.html

In file.js (I know varible found is working, tested using an alert).

chrome.extension.sendRequest({foundlinks: found}, function(response) {
 console.log(response);
});

In Popup.html:

function pulllinks(){

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {

    document.getElementById("box").value = request.foundlinks;

  sendResponse({});
});

And on the form in popup.html:

<input type = "button" onclick="pulllinks();" name = "box" id="box" value = "Grab Links From Page"  /> 

However, its not doing anything. Any ideas?

Thanks!

Upvotes: 0

Views: 221

Answers (2)

serg
serg

Reputation: 111325

You need to be sending requests in the opposite direction - from popup to content script:

popup.html:

function pulllinks(){
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {cmd: "findLinks"}, function(response) {
            document.getElementById("box").value = response.foundlinks;
        });
    });

}

file.js:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.cmd == "findLinks") {
        //calculate "found" value and send it back
        sendResponse({foundlinks: found});

    }
});

Upvotes: 1

mattsven
mattsven

Reputation: 23293

First of all, your listener for onRequest should exist from the start, so move it outside of the pulllinks function. Secondly, how are you making sure that your sendRequest is being fired while the popup is open?

Upvotes: 1

Related Questions