开发者

Message Passing in Chrome

Have a small doubt in how message passing works in chrome using content scrips. I modified the default example (http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/messaging/timer/) for message passing given in the chromium documentation to the one that looks below :

popup.html

function testRequest() {

  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {counter: "getHTML"}, function handler(response) {
      alert("Inside Client = "+response.counter2);
    });
  });
}

and my content script looks like this :

page.js

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    alert(reques开发者_JAVA百科t.counter);
    alert("Inside server .. Req Counter = "+request.counter);
    sendResponse({counter2: "5"});
  });

When I execute the testRequest from popup.html, the content script is getting called as expected. I do get both the alerts i have declared with their respective values. But my popup.html response code doesnt seem to be called .. The alert I have inside the popup.html - alert("Inside Client = "+response.counter2); is not being executed.

On the other hand, If i have a debug point inside the client, its working ! Kinda strange.. Can somebody tell me how and why this is happening ?

Thank you in advance..


your code is correct. I am mistaken what I said before.

Believe me when I say it, I was puzzled why it didn't work. It turned out to be that I am running the browser action on the chrome://extensions/ page. In Chrome Extensions, the API will not let you execute or send any requests to that page. Do it on a normal page like Google.com and you will see your popup.

You cannot show an alert dialog within popup page.

That is why you don't see: alert("Inside Client = "+response.counter2); }

If you want to see it working, you can add a console logger and view it within the Web Inspector. Replace the alert with: console.log(response.counter2);


As far as I can tell, alerts from a popup will only appear if the popup is open.

You see the alert when you're debugging the popup because the debugger keeps the popup open.

I'm pretty sure there are also no problems with creating alerts from the background page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜