I'm successfully sending a file from localhost:8888
to localhost:8080
(different domain in production), but I can't read the HTTP response after the transfer finishes.
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://localhost:8888" from accessing a frame with origin "http://localhost:8080". The frame requesting access set "document.domain" to "localhost", but the frame being accessed did not. Both must set "document.domain" to the same value to allow access.
To send the file, for compatibility support, I'm trying to get this to work for <form>
based file uploads; not XHR
based. This is the basic HTML structure:
<form target="file-iframe" enctype="multipart/form-data" method="POST" action="invalid">
<input type="file" id="file-input" class="file-input" title="select files">
</form>
<iframe src="javascript:false;" id="file-iframe" name="file-iframe"></iframe>
To insert the <iframe>
element into the DOM, I do the following:
document.domain = document.domain;
var domainHack = 'javascript:document.write("<script type=text/javascript>document.domain=document.domain;</script>")';
var html = '<iframe id="file-iframe" name="file-iframe"></iframe>';
var parent = document.getElementById('wrapper');
var iframe = UTILS.createDomElement(html, parent);
iframe.src = domainHack;
UTILS.attachEvent(iframe, 'load', function(e) {
// this throws the above SecurityError
var doc = iframe.contentDocument || iframe.contentWindow.document;
// do other stuff...
});
Before I submit the form, I set the action
attribute on the <form>
to be the target cross-domain URL:
action="http://localhost:8080/"
After submitting the <form>
, the <iframe>
's load
event is fired, and I try to access the <iframe>
's content to read the HTTP response. However, doing so throws the above error since this is is a cross-origin request, and I don't have access to the <iframe>
's content.
I thought the document.domain
hack would work, but the error message is telling me that the iframe
did not set the domain to localhost
, even though I set the iframe
's src
attribute to the domainHack
variable, which seems to execute.
Any ideas as to what I might be doing wrong? How can I set document.domain
to be localhost
for both the <iframe>
and its parent (which is the current page).
I've read through several StackOverflow questions, some MDN articles, and other random results on Google, but I haven't been able to get this to work. Some stuff I've looked through already: