views:

21

answers:

1

In my background (background.html) page I have the following js:

function capturePage(){
  chrome.tabs.captureVisibleTab(null, function(img){
    var screenshotUrl = img;
    chrome.tabs.create({"url":"history.html"}, function(tab){
      var t = tab;
      var addImage = function(){
        var view = chrome.extension.getViews()[0];
        view.setImageUrl(screenshotUrl);
      }
      chrome.tabs.onUpdated.addListener(addImage);
    });
  });
 }

 chrome.browserAction.onClicked.addListener(capturePage);

and in history.html I have:

<html>
<head>
  <title></title>
  <script>
    function setImageUrl(url){
      document.getElementById("target").src = url;
    }
  </script>
</head>
<body>
  <img id="target" src="" >
</body>
</html>

However, "view.setImageUrl(screenshotUrl)", in background.html, fails as it says the view has no such function. Just to be clear, I'm trying to access a function within history.html AND pass a parameter to it (screenshotUrl). EDIT: re Serg's suggestion I replaced the var addImage function in background with the following:

var port = chrome.tabs.connect(tab.id,{name: "history_connect"});
port.postMessage({mType:"url",url:screenshotUrl});

Then added a listener on the history page... worked!

+1  A: 

I haven't used getViews() before so I can't comment on that (what does console say when you dump chrome.extension.getViews() into it?), but here is couple workarounds:

  • Pass your url as get parameter during tab creation (history.html?url=<urlencoded_url>)
  • Use requests. chrome.extension.sendRequest({url:url}); in bkgd page and chrome.extension.onRequest.addListener() in history.html
  • Use "pull" instead of "push". In history.html you can use chrome.extension.getBackgroundPage().getMyUrl()

I would use the first solution as it is the easiest and fastest.

serg
The first solution is indeed quick and easy for 1 url/image, but would it work for 60 urls?
LDK
@LDK I think it still would but if you need to pass so many data then probably other solutions would be better. If you are passing big amounts of data it would be more efficient to use long lived connections: http://code.google.com/chrome/extensions/dev/messaging.html#connect
serg