I have the same exact problem as the user in this question. I am using this code:
function imgData(img) {
var src_canvas = document.createElement('canvas');
src_canvas.width = this.width;
src_canvas.height = this.height;
var src_ctx = src_canvas.getContext('2d');
src_ctx.drawImage(img, 0, 0);
var src_data = src_ctx.getImageData(0, 0, this.width, this.height).data;
}
And it always generates this error on Chrome:
Uncaught SecurityError: An attempt was made to break through the security policy of the user agent. Resources.js:27
Unable to get image data from canvas because the canvas has been tainted by cross-origin data. Resources.js:27
I am extremely new to JavaScript and have no idea what the issue is here. The internet seems to be at a loss today as well so I am now here. The answers to the question I referenced refer to the issue being he was trying to use images from outside sources (outside of his file system). The problem is, I'm not. I am just running the files in Chrome on my file system. The image is also in my file system and not anywhere I would think would merit a security error. Any thoughts? Am I being a moron?
Are you accessing your HTML / JavaScript as files directly from your filesystem, instead of behind a webserver? If so, try the latter, most browsers will have cross-domain security issues if you ask them to grab data outside of a webserver (even if they're in your own filesystem).
Related
I'm trying to load an image called "border.bmp" so that I can use it as a texture for WebGL. Here's how I reference the image.
var img;
function preload() {
img = loadImage("assets/border.bmp");
}
I then get this error in the console.
Access to Image at 'file:///C:/P5.js/empty-example/assets/border.bmp' from
origin 'null' has been blocked by CORS policy: Invalid response. Origin
'null' is therefore not allowed access.
What is this error message? What does it mean? How do I load the image?
The comment by gman and the answer by Dale are both correct. I highly recommend you take the time to understand exactly what they're saying before you downvote or dismiss them.
CORS stands for cross-origin resource sharing, and basically it's what allows or prevents JavaScript on one site from accessing stuff on another site. A quick google search of "JavaScript CORS" or just "cors" will give you a ton of information that you should read through.
So if you're getting a CORS error, that means that the site that holds your image is not letting the site that holds your code access the image. In your case, it looks like you're loading stuff from a file: URL, which is not being loaded from a server. That's what the Origin null part of the error means.
So, step one is to listen to gman's comment and run your sketch from a local webserver instead of using a file: URL. His comment already contains links explaining how to do that, or you could use the P5.js web editor or CodePen or any other basic web host.
The most common setup is to include the image files in the same server as the code, so that should be pretty much all you need to do. But if you're storing the images at a different URL than the code, then step 2 is to follow Dale's answer and setup your image server to allow requests from your code server.
While the following doesn't directly answer the OP question, it can help others, like me, that ended up here searching for P5.JS CORS.
To bypass CORS restrictions simply add the blocked URL after https://cors-anywhere.herokuapp.com, i.e.:
var = 'https://cors-anywhere.herokuapp.com/http://blocked.url'
P5.JS Example:
Lets say you want to load a remote mp4 video (it can be any file-type) using P5.JS from a server that doesn't have CORS enabled, for these situations, you can use :
var vid;
function setup() {
vid = createVideo(['https://cors-anywhere.herokuapp.com/http://techslides.com/demos/sample-videos/small.mp4'], vidLoad);
}
// This function is called when the video loads
function vidLoad() {
vid.play();
}
UPDATE:
The demo server of CORS Anywhere (cors-anywhere.herokuapp.com) is meant to be a demo of this project. But abuse has become so common that the platform where the demo is hosted (Heroku) has asked me to shut down the server, despite efforts to counter the abuse (rate limits in #45 and #164, and blocking other forms of requests). Downtime becomes increasingly frequent (e.g. recently #300, #299, #295, #294, #287) due to abuse and its popularity.
To counter this, I will make the following changes:
The rate limit will decrease from 200 (#164) per hour to 50 per hour.
By January 31st, 2021, cors-anywhere.herokuapp.com will stop serving as an open proxy.
From February 1st. 2021, cors-anywhere.herokuapp.com will only serve requests after the visitor has completed a challenge: The user (developer) must visit a page at cors-anywhere.herokuapp.com to temporarily unlock the demo for their browser. This allows developers to try out the functionality, to help with deciding on self-hosting or looking for alternatives.
CORS Stands for Cross-origin resource sharing. By default WebGL will block any resource (images, textures, etc) from any external origin. WebGL thinks the local resource is from an external origin.
You can bypass this by using img.crossOrigin = "";
I'm not an expert in webGL, all this information was found here
If you want to load local images in P5, you can use the drawImage() function of the canvas instead of image() function of the P5.js
let img;
function setup() {
createCanvas(windowWidth,windowHeight);
img = new Image();
img.src = "assets/smiley.png";
}
function draw() {
drawingContext.drawImage(img,mouseX,mouseY);
}
I have tried to getImageData but in the console I see this error:
Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
at HTMLImageElement.img.onload (file:///C:/Users/HOME/Desktop/programmi/HTML-Javascript/caso/graphic/imgData/arc/main.js:16:17)
This is my JavaScript and HTML code:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
width = canvas.width = 434,
height = canvas.height = 362;
var img = new Image();
img.src = 'https://cdn.pixabay.com/photo/2017/02/26/12/27/oranges-2100108_640.jpg';
//img.crossOrigin = 'Anonymous';
img.onload = function() {
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(10, 10, 11, 11);
console.log(data)
};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id='canvas'></canvas>
<script type="text/javascript" src='main.js'></script>
</body>
</html>
Let me guess ... you're using Google Chrome as your browser. Which is the most problematic browser for this issue.
The issue centres upon what is known as cross-site security. in short, modern browsers are designed to prevent cross-site content from being loaded into a browser, except under special conditions, in part to stop malicious code being injected into web pages that you load.
This extends to images and HTML5 canvas data. The reason being, that some sneaky individuals discovered, early in the days of the HTML5 canvas being provided, that they could use it to provide an image snapshot of your current browser contents, and send that snapshot back to be perused at leisure. If you were browsing your bank's website at the time, and engaging in sensitive financial transactions online, whoever used this technique would quickly be able to find out about your finances, and possibly even pose as you to raid your account.
That's one of the reasons restrictions on cross site content were introduced.
Now, of course, there are legitimate reasons for having cross-site content. Such as having one's fonts or images stored in a separate repository. Trouble is, the cross-site restrictions impact upon legitimate uses as well as illegitimate ones.
Consequently, in order to use images cross-site, you have to do so in conformity with the CORS protocol. But, to do this, you need your images to be provided by a web server that's set up to handle CORS transactions. Simply setting the img.crossOrigin property of an Image object to "anonymous" won't work on its own: you need the server that's sending the images, to be set up to respond to the pre-flight options request that your browser will send, before allowing the image to be treated as acceptable from a security standpoint.
Which means, that to solve your problem, you need either, to:
[1] Install a local web server to perform this task for you - this option involves much tedium reading the web server manual, in order to set the server up properly, and much editing of configuration files;
[2] Write your own server to run under node.js or similar - this option involves even more tedium learning how to write your own web server, and make that server handle CORS transactions properly.
Now, if you're testing code offline in the "old school" manner, Firefox will let you access images from the same directory as your code, via the file:// protocol, and won't complain. Firefox apparently has enough intelligence to realise that an image being extracted from the same directory of your hard drive as your web page, constitutes a same-origin image.
If, however, you're using Google Chrome, it won't. At least, not unless you run it using special command line parameters. Even then, Chrome has a propensity to throw temper tantrums when asked to handle this sort of request. It's an issue I wrestle with frequently, and though some might be tempted to tell me to do my testing in Firefox to avoid these woes, Chrome's internal debugger is, for me at least, far more pleasant to use than Firefox's debugger, which, in my current Firefox installation, crawls like a snail on Mogadon, and exhibits a friendliness and smoothness of use reminiscent of a cocaine-soaked pit viper.
So, if you're using Chrome, because like me, you like its internal debugger, you're stuck with the two options I've given above. Either install a web server (Apache, Nginx, take your pick) or install Node.js and write your own. Neither option is easy.
HTML page SVG definition
<embed id="sv" src="test.svg" type="image/svg+xml" width="1720" height="938">
Javascript :
//var eID = document.getElementById("ENV");
var S = document.getElementById("sv");
var SD;
S.addEventListener('load', function()
{
SD = S.contentDocument;
SD = S.getSVGDocument();
// Operate upon the SVG DOM here
});
as you see, my SVG is defined by an embed element, When i tried to access this SVG object, i get undefined in Chrome (SD variable in above code), But it is working fine in Firefox and I can access the elements inside SVG.
So, the issue is only with Chrome. Whats the problem and how to resolve it?
It is because of a security restriction in Chrome which prevent access to external SVG by javascript when you open an html page through file system not from a local or online server.
the Error will be:
Uncaught DOMException: Failed to execute 'getSVGDocument' on
'HTMLEmbedElement': Blocked a frame with origin "null" from accessing
a cross-origin frame.
you can use a local server, or disable the Same-Origin Policy by closing chrome and restart it with the --disable-web-security command line argument (see this answer).
Note that this will not occur in production when you publish your files to an online host!
Also, the Firefox does not have such limitation. As mentioned in comments, It has a simple limitation: the files should be in same folder (or a sub-folder beside the page you have opened)
My Chrome version is 31.0.1650.57
I'm learning THREE.js and downloaded a planet sample from https://github.com/jeromeetienne/threex.planets/
But when I run the earth.html
a strange error happens as the title says:
THREE.WebGLRenderer 59 three.min.js:424
Cross-origin image load denied by Cross-Origin Resource Sharing policy. earth.html:1
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': the canvas has been tainted by cross-origin data. threex.planets.js:73
(anonymous function) threex.planets.js:73
I looked through the code and find something that might be related to this error:
THREEx.Planets.baseURL = '../'
...
map: THREE.ImageUtils.loadTexture(THREEx.Planets.baseURL+'images/earthmap1k.jpg'),
But I don't know how to fix it, I'm relatively new to javascript,
hope someone would help me out!
Thanks a ton!
Are you running this on a local filesystem (double-clicking the html file) or are you running it on a web server? If you run it on a web server you should avoid the cross-origin permission problems. (This is a security feature of browsers such as Chrome.)
I fixed this problem by installing Node.js and running a local server to open this html!
Something like this should fix it.
var imageObj = new Image()
imageObj.onload = function(){
THREE.ImageUtils.loadTexture(imageObj)
// or maybe load image into canvas?
}
imageObj.crossOrigin="anonymous"
imageObj.src = THREEx.Planets.baseURL+'images/earthmap1k.jpg'
Use crossOrigin="anonymous" in your image tag as below.
<img src="SOMETHING" crossOrigin="anonymous" />
I konw that problem is you need to run your project or the Three.js example in server environment,like the above answer run your code in nodejs or Appserv these local serve
I have a standard 3-frame layout; "fnav" on the left, "fheader" at the top and "fcontent" below the header. All files are located locally on the hard drive.
This is the JS function that is throwing the error:
function writeHeaderFrame() {
try {
var headerFrame = window.top.frames['fheader'];
var headerTable = document.getElementById('headerTable');
if (headerFrame && headerTable) {
headerFrame.document.body.style.backgroundColor = "Black";
var headerFrameBody = headerFrame.document.documentElement.childNodes[1];
headerFrameBody.innerHTML = headerTable.innerHTML;
} else if (headerTable) {
// there is a headerTable, but no headerFrame
headerTable.style.display = 'inline' // show the headerTable
}
} catch (e) { alert('from header.js, writeHeaderFrame(): ' + e.message); }
}
Clicking on a link in fnav (or initially loading the frameset) loads content into fcontent, then a JS file in fcontent loads the "header" frame... or it is supposed to, anyway. The Javascript runs fine initially, but whenever a link is clicked I get the following error:
Permission Denied To Get Window.document
I am unable to determine why. Any and all suggestions would be appreciated.
First off, please post the code being run when you click those links, and their html.
secondly, did you have a typo there? Window.document should be window.document, should it? (lowercase w)
Edit response to changes in OP question
Without the html it's a little hard to say, but If I were taking a stab in the dark, I'd say this line:
headerFrame.document.body.style.backgroundColor = "Black";
is causing the error. It looks like headerFrame is on a different domain and you don't, for security reasons, have permission to modify the contents of that frame. Of course, some of the following lines will also have the same issue.
Also see http://userscripts.org/topics/25029 and http://www.webdeveloper.com/forum/showthread.php?t=189515 for similar cases.
Edit 2
From Mozilla Development Center
Note: Firefox 3 alters the security for windows' documents so that only the domain from which it was located can access the document. While this may break some existing sites, it's a move made by both Firefox 3 and Internet Explorer 7, and results in improved security.
(see https://developer.mozilla.org/En/DOM/Window.document)
I would guess you're trying to manipulate the window or document from a different origin. HTML5 (and all modern browsers, even IE :D ) enforce (or attempt to enforce) what is called "The Same-Origin Policy". Basically JS from one origin cannot interact with the DOM of a document or window from a different origin.
What is an origin? At a basic level you could substitute domain for origin and almost be right, but the full set of rules are
You must have the same domain
The same port (eg. code on example.com:80 cannot reference the DOM of a page a example.com:8080)
The same protocol (eg. http://example.com is a different origin from https://example.com)
lastly, redirects also matter so (http://example.com -> http://example.com/?redirect=http://evil.com with the server responding with a 3xx redirect to http://evil.com will result in a different origin)
In all liklihood firefox has merely tightened up one area where they did not apply the same origin policy in the past.
Apparently, the user in question updated his installation without changing the following setting to "false", which allows local documents to have access to all other local documents.
pref("security.fileuri.strict_origin_policy", true);
Which explains why I was unable to duplicate the error on my machine.
Many thanks to all for your assistance.
Have you tried installing Firebug and figuring out which line is throwing the error? I'm guessing that since the question is tagged Firefox you are seeing this occur in it.
It'd be most helpful if you could post a template HTML page using this Javascript.
Is the script/frame pages all on the same domain? If not, this is expected. You can't access window.document from another window if they are not on the same domain.