Reputation: 3616
Having a problem while passing messages using content scripts in Google chrome extension dev My Code structure looks like this:
popup.html:
var oList;
function getHTML()
{
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
oList = response.dom;
});
});
alert("oList = "+oList );
}
and my content Script looks like this:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if(request.action == "getHTML"){
sendResponse({dom: document.getElementsByTagName("HTML").length});
}
});
When I debug my code by putting a breakpoint at "oList = response.dom;
" in my popup.html, i get the
right value set from the content script. But while executing the extension, the "alert("oList = "+oList );
" code
from the popup.html seems to be executing first before it goes to the server.. And therefore, its value is
not being set.. Can somebody tell me if I am wrong somewhere ?
Upvotes: 1
Views: 1284
Reputation: 111335
Most Chrome API methods are asynchronous. It means that when you are calling them the script doesn't wait for their response and simply continues executing. If you want to execute something on response you should put it inside callback function:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
oList = response.dom;
alert("oList = "+oList );
});
});
Upvotes: 5