moodyak
moodyak

Reputation: 110

Getting data from Google Chrome Webview to Caller/Parent window

I'm working on a Chrome Kiosk Application (So packaged app limitations apply) that's essentially a web browser that will be deployed to some Chrome devices. I'm looking to support screenshots, and I'm using HTML2Canvas to do this, but I need to store them to be uploaded later on.

I'm calling HTML2Canvas by using webview.executeScript{file:} with a callback. In the callback I'm executing the actual html2canvas call

  webview.executeScript({ file: "kiosk/html2canvas.js" }, handleHTML2CanvasInjected);

  function handleHTML2CanvasInjected(event) {
     var webview = document.querySelector('webview');
     webview.executeScript({code: "html2canvas(document.body).then(function(canvas){ //whatever });"});
   }

I can append the canvas object to the body and see that the screenshot is working. However, I need this to be returned to the caller.

I've tried to use localStorage, but it seems the webviews storage and the caller's storage are two different things.

It really boils down to the fact that I need to be able to communicate "stuff" between a Webview and the Window that created the Webview.

Upvotes: 1

Views: 1252

Answers (1)

Schnodderbalken
Schnodderbalken

Reputation: 3477

Load the webview with the following lines to make sure everything is loaded once you execute the script it:

webview.addEventListener("contentload", function () {
  webview.executeScript({file: "myscript.js"}, function(result) {});
}

Within the script you can for example call html2canvas. You can communicate the result back to the main script by using the messaging system:

var body = document.querySelector("body");

html2canvas(body, {
    onrendered: function(canvas) {
        chrome.runtime.sendMessage({canvas:canvas.toDataURL()});
    }
});

Then just react on the onMessage-Event in the main script:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
       if(request.canvas) {
          plugin.data.canvas = request.canvas;
          // do something with the screenshot
        }
    }
);

Hope that helped! :)

[edit]

Just found this: https://code.google.com/p/chromium/issues/detail?id=326755

It seems like they are working on a native function. This would then be called like this:

webview.captureVisibleRegion({ format: "png" }, function(dataUrl) { 
  var image = new Image();
  image.src = dataUrl;
  document.body.appendChild(image);
});

Upvotes: 1

Related Questions