简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM