Shan
Shan

Reputation: 2832

How to pass data between the contentscript and background.html in Chrome extensions

I am passing the data from content script to background.html in the below code but it doesn't works for me due to some reason..Here is the code..

Contentscript.js

    var a1 ="Shan";
    chrome.extension.sendRequest({method:"text",txt:a1}, function(response) {
      d=response.data;
      alert(d);
    });

background.html

   if(request.method == "text")
   {
       sendResponse({data:request.key});
   } 
   else
   {
     sendResponse({data:request.key});
   }    

My question is why I am not able to pass the variable "a1" to background.html?? Whether it can't be done?

Upvotes: 0

Views: 394

Answers (1)

Rob W
Rob W

Reputation: 349222

Because the key is named txt, not key.

chrome.extension.sendRequest({method:"text",txt:a1}
                                            ^^^ Your definition: txt

 sendResponse({data:request.key});
                            ^^^ Should be txt as well

Warning: I've experienced that you cannot recycle the sendResponse method. After firing sendResponse, the extension will not responde to future sendResponse calls.
So, only one sendResponse for each chrome.extension.sendRequest.

Upvotes: 1

Related Questions