Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas has been tainted by cross-origin data via local chrome:// extension URL

I am working on a google chrome extension and I am trying to load an image that is bundled with the extension into a canvas.

var canvas = document.createElement('canvas');
canvas.width = 470;
canvas.height = 470;
var context = canvas.getContext('2d');
var image = new Image();
image.addEventListener('load', function(){
     //process
});
image.src = chrome.extension.getURL("asset/gotcha.png");

When I execute the code in a content script I am getting:

Unable to get image data from canvas because the canvas has been  tainted by 
cross-origin data.

Is there a way to avoid this? I have successfully embedded images, audio, video and flash directly into target sites without any those issues. The resource is listed under the web_accessible_resources in the manifest file.

like image 868
Stan Wiechers Avatar asked Nov 10 '13 20:11

Stan Wiechers


1 Answers

Based on ExpertSystem's approach I got a simple solution.

First part in the JavaScript of the background page where a canvas can be created without throwing a security exception.

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.message == "convert_image_url_to_data_url") {
      var canvas = document.createElement("canvas");
      var img = new Image();
      img.addEventListener("load", function() {
        canvas.getContext("2d").drawImage(img, 0, 0);
        sendResponse({data: canvas.toDataURL()}); 
      });
      img.src = request.url;
      return true; // Required for async sendResponse()
    }
  }
)

Second part for the content script:

//@success is the callback
function local_url_to_data_url(url, success) {  
  chrome.runtime.sendMessage(
    {message: "convert_image_url_to_data_url", url: url}, 
    function(response) {success(response.data)}
  );    
}
like image 195
Stan Wiechers Avatar answered Nov 13 '22 02:11

Stan Wiechers