NS_ERROR_UNEXPECTED in Firefox when uploading file from iframe - javascript

I'm trying to allow users to upload files without causing the page to change when they upload the files. To do this, I'm using an iframe, which I'm adding a form and a file input to, then submitting the form within the (hidden) iframe. This works just fine on Chrome, but not on Firefox.
Below is code which causes this problem.
<!DOCTYPE html>
<html>
<head>
<style>
#pretty-button { background: blue; }
#hidden-uploader { display: none; }
</style>
<script>
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('pretty-button');
var filename_output = document.getElementById('filename');
var upload_iframe = document.getElementById('hidden-uploader');
btn.addEventListener('click', function() {
document.body.appendChild(upload_iframe);
_document = upload_iframe.contentDocument;
var form = _document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('action', '.');
var file_input = _document.createElement('input');
file_input.setAttribute('type', 'file');
file_input.setAttribute('name', 'document');
form.appendChild(file_input);
_document.body.appendChild(form);
file_input.click();
file_input.addEventListener('change', function() {
console.log('file selected');
form.submit();
upload_iframe.addEventListener('load', function() {
console.log('file uploaded');
});
});
});
});
</script>
</head>
<body>
<button id="pretty-button">Choose a File</button>
<span id="filename"></span>
<iframe id="hidden-uploader"></iframe>
</body>
</html>
On firefox, this fails with NS_ERROR_UNEXPECTED: on line 33, which is form.submit(), when a file is selected.
Any idea what might be happening here?

I think I figured the problem, which is in the line
document.body.appendChild(upload_iframe);
This causes the iframe to reload itself, which means that the contentDocument of the iframe before it is re-appended to the document body is different from the contentDocument of the iframe after it is re-appended to the document body. The reloading occurs while the file dialog is open.
This can be verified by making the following changes:
<!DOCTYPE html>
<html>
<head>
<style>
#pretty-button { background: blue; }
#hidden-uploader { display: none; }
</style>
<script>
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('pretty-button');
var filename_output = document.getElementById('filename');
var upload_iframe = document.getElementById('hidden-uploader');
btn.addEventListener('click', function() {
document.body.appendChild(upload_iframe);
_document = upload_iframe.contentDocument;
var form = _document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('action', '.');
var file_input = _document.createElement('input');
file_input.setAttribute('type', 'file');
file_input.setAttribute('name', 'document');
form.appendChild(file_input);
_document.body.appendChild(form);
file_input.click();
// So far, the iframe hasn't reloaded.
file_input.addEventListener('change', function() {
/* Because the iframe loads in less time than it
* takes for the user to select a file, the iframe
* has now reloaded, and _document refers to the
* contentDocument of an iframe which is no longer
* attached to the page.
*/
console.log('file selected');
var _newDocument = upload_iframe.contentDocument;
console.log(_document === _newDocument); // false in Firefox, true in Chrome
form.submit();
upload_iframe.addEventListener('load', function() {
console.log('file uploaded');
});
});
});
});
</script>
</head>
<body>
<button id="pretty-button">Choose a File</button>
<span id="filename"></span>
<iframe id="hidden-uploader"></iframe>
</body>
</html>
By removing the offending line, the above starts working in Firefox.

Related

Nested Iframe doesn't have content after reload on Mozilla

I have this problem on Mozilla (worked perfectly on Chrome) where the nested Iframe doesnt have content after reload (only empty header and body tag)
Somehow you can click on the search bar and enter (instead of reload) to open again and all iFrame will load as intended
---------Working Snippet---------
https://codesandbox.io/s/determined-edison-9rwhwv?file=/index.html
Body index.html
<body>
<div>Index</div>
<iframe id="iframe"></iframe>
<script>
(function () {
var b = document.getElementById("iframe");
b.setAttribute("src", "iframe.html?" + Math.random() * 100);
})();
window.addEventListener('beforeunload', function (event) {
console.log('I am the 1st one.');
});
window.addEventListener('unload', function (event) {
alert('unLoad')
});
</script>
</body>
body iframe.html
<body>
<header>
IFRAME1
</header>
<iframe id="iframe2"></iframe>
<script>
(function () {
var b = document.getElementById("iframe2");
b.setAttribute("src", "iframe2.html?" + Math.random() * 100);
})();
window.addEventListener('beforeunload', function (event) {
console.log('frame 1 before unload.');
});
window.addEventListener('unload', function (event) {
console.log('frame 1 unload.');
});
window.addEventListener('pagehide', (event) => {
if (event.persisted === true) {
console.log('This page *might* be entering the bfcache.');
} else {
console.log('This page will unload normally and be discarded.');
}
});
</script>
</body>
Body iframe2.html
<body>
<header id="h2">
this is iframe 2
</header>
<script src="iframe2.js"></script>
</body>
I read something about bfcache, which is why i tried to put unload event to negate bfcache.
Found this thread with help from zer00ne about mixed content
Mixed Content warning on Chrome due to iframe src
But this seems to be a security issue to do
I got it working by calling the function after load event
window.addEventListener('load', function () {
function setIframe() {
var b = document.getElementById("iframe");
b.setAttribute("src", "iframe.html");
}
setIframe();
})
Hope this helps anyone.

IE 11 onload is never called

My web page has following javascript
function LoadPDF(filename)
{
var loc = filename;
document.getElementById("pdf").setAttribute("src", loc);
if (window.addEventListener) {
document.getElementById("pdf").addEventListener("load", LoadPrint, false);
}
else if (window.attachEvent) {
document.getElementById("pdf").attachEvent("onload", LoadPrint);
}
else {
document.getElementById("pdf").onload = LoadPrint;
}
}
function LoadPrint() {
alert('fired!');
if (document.getElementById("pdf").src !== "") {
var frm = document.getElementById("pdf");
frm.contentDocument.getElementById("pdf").contentWindow.print();
}
}
The LoadPDF is called from code behind. "pdf" is my iframe. When the pdf is loaded into the iframe I want to call LoadPrint. But the trouble is in IE 11 its never called.
Can anyone please help?
This is an IE11 bug, which MS refuses to fix because they consider it a feature bug and they no longer fix that kind of bugs for old browser versions.
A workaround to this bug, is to load the pdf file inside an other page iframe and then load that page inside your iframe. A simple javascript pdf loader with a file argument:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PDF Loader</title>
<style type="text/css">
html, body {
border:0;
margin:0;
height:100%;
overflow-y:hidden;
}
#pdf {
border:0;
margin:0;
width:100%;
height:100%;
}
</style>
</head>
<body>
<iframe id="pdf"></iframe>
<script type="text/javascript">
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var pdf = getParameterByName('pdf');
document.getElementById('pdf').setAttribute('src', pdf);
</script>
</body>
</html>
You can use it with the <filename.html>?pdf=<pdf_file_to_load>.
Then you just change your code to load the pdf file through that loader like this:
function LoadPDF(filename)
{
var loc = "pdf-loader.html?pdf="+filename;
document.getElementById("pdf").setAttribute("src", loc);
if (window.addEventListener) {
document.getElementById("pdf").addEventListener("load", LoadPrint, false);
}
else if (window.attachEvent) {
document.getElementById("pdf").attachEvent("onload", LoadPrint);
}
else {
document.getElementById("pdf").onload = LoadPrint;
}
}
function LoadPrint() {
alert('fired!');
}
LoadPDF('http://www.pdf995.com/samples/pdf.pdf');
Now the LoadPrint function is called on iframe load event even on IE11.
Here is my working example you can even test with IE11: http://zikro.gr/dbg/html/ie11-iframe-pdf/
Here you can see a screen capture with the 10MB PDF loading and only after it finish loading it fires the load event and alerts the message:
I don't know if this is your specific issue in this instance, but make sure you bind your listeners to the element before you assign it's src attribute. If the item is in cache it is possible for the load event to fire before you bind to it, thus missing it entirely.

Run javascript function on loaded page

Very new to Javascript, so working on my first project. Attempting to run a script that gathers listing numbers, opens them in a URL and clicks an element on the loaded page. I can't get .click() to run on the resulting loaded page.
I've tried to set the logIn function to only run once the resulting page has loaded, but it doesn't seem to be doing the trick. AM I missing something basic?
var listingNum = prompt("Listing numbers").split(" ");
logIn = function(){
if(document.readyState === "complete"){
document.getElementById('SignInAsMemberLinkHeader').click();
}
};
for(i = 0; i < listingNum.length; i++){
window.open("http://www.website.com" + listingNum[i],"_self");
setInterval(logIn(), 4000);
};
Okay, the following test harness worked for me. I had to change your _self reference to _blank, so that each page loads separately and doesn't overwrite the operation of the parent page. You then just handle the load event of each window that is instantiated using window.open(). This was the part you were missing. You weren't handling the load events of the loaded windows.
You may wish to check that the SignInAsMemberLinkHeader element exists prior to calling click() on it, but I'll leave that up to you to implement.
NB this will not work if cross site scripting restrictions apply.
Hope this helps :)
<!DOCTYPE HTML>
<html>
<head>
<title>External Page Opener Test</title>
<meta charset="UTF-8">
<style>
body {
background-color:cornflowerblue;
color:white;
font-family:Tahoma,Arial,sans-serif;
}
</style>
<script>
window.addEventListener('load', init, false);
function init(event) {
var listings = prompt("Listing numbers:");
if (listings) {
var listingNum = listings.split(" ");
for (i = 0; i < listingNum.length; i++) {
// I used my local desktop and 3 test HTML files,
//each with a button click and handler on them.
var url = "file:///C:/Users/******/Desktop/" + listingNum[i];
var handle = window.open(url, "_blank");
handle.addEventListener('load', extPageLoaded, false);
}
} else {
console.log('No listings were entered.');
}
}
function extPageLoaded(event) {
const TIME_TO_WAIT_IN_MILLISECONDS = 4000;
setTimeout(
function() {
event.target.getElementById('SignInAsMemberLinkHeader').click();
},
TIME_TO_WAIT_IN_MILLISECONDS
);
}
</script>
</head>
<body>
</body>
</html>

Copy a text when a link or button is clicked

I am new to website development and try to figure out how can I make my user automatically copy a code in to his/her mouse(clip board) when clicked on a link (using html, php or javascript). For example, I am trying to create this personal website, when a user click on a link or a button in my website, it should automatically copy that text code to the clip board. I have seen sites like retailmenot.com do this: Example:-
Please show me with an example if you can
Updated:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$("#link").click(function(){
var holdtext = $("#clipboard").innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
});
</script>
</head>
<body>
<hr>
Click here to copy the Code <button onclick="copyToClipboard()">Copy Text</button>
<hr>
</body>
</html>
Here is the function which might can help you or future referer.
function copyToClipboard(id) {
var text = $("#td_id_" + id).text(); //getting the text from that particular Row
//window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}
Unit test in all Browser not done.
try this.
$("#link").click(function(){
var holdtext = $("#clipboard").innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
});

Why doesn't IE8 handle iframe onload events?

Sample code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function on_iframe_load() {
document.getElementById('iframe_a').onload = function() {
alert('Thanks for the visit!');
};
}
</script>
</head>
<body>
<iframe name="iframe_a" id="iframe_a"></iframe>
Go!
</body>
</html>
It works in all major browsers with no problem, but IE8 (and probably prior versions) don't understand it.
Update: Just came up with a solution, but I'm not sure if it's right coding. Please review:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
var clicked = false;
function activate() {
clicked = true;
}
function pop() {
if (clicked) {
alert('Thanks for the visit!');
};
}
</script>
</head>
<body>
<iframe name="iframe_a" onload="pop();"></iframe>
Go!
</body>
</html>
Using inline attribute on iframe seems to fix this issue in IE8:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function onIframeLoad(iframe) {
if(iframe.src) {
alert('Thanks for the visit!');
}
}
function onLinkClick(url) {
document.getElementById('iframe_a').src = url;
}
</script>
</head>
<body>
<iframe id="iframe_a" onload="onIframeLoad(this);"></iframe>
Go!
</body>
</html>
update by request:
You should try writing more unobtrusive javascript. Writing code in such way may prevent you from such strange bugs in IE.
<!DOCTYPE html>
<html>
<body>
<iframe id="display-frame"></iframe>
Go!
<script>
window.onload = function() {
var iframe = document.getElementById('display-frame'),
link = document.getElementsByTagName('a')[0];
// load handler
function onIframeLoad() {
alert('Thanks for the visit!');
}
// event handlers
if(iframe.addEventListener) iframe.addEventListener('load', onIframeLoad, false);
else if(iframe.attachEvent) iframe.attachEvent('onload', onIframeLoad);
link.onclick = function() {
iframe.src = this.href;
return false;
}
};
</script>
</body>
</html>
It seems you can't add a load listener to an iFrame in IE using the DOM property once the page has loaded.
But you can use attachEvent, so:
function on_iframe_load() {
function foo() {
alert('Thanks for the visit!');
};
var el = document.getElementById('iframe_a');
if (el.attachEvent) {
el.attachEvent('onload',foo);
} else if (el.addEventListener) {
el.addEventListener('load', 'foo', false);
}
}
I was testing in IE 6 and reversed the usual test order so that attachEvent is used in preference to addEventListener. You may want to test more recent versions of IE to see if the opposite order works and also test other IEā€“like browsers such as Opera.
Edit
Modified the code after testing (silly me) to use addEventListener. Here's something that works in IE and others:
function on_iframe_load() {
function foo() {
alert('Thanks for the visit!');
};
var el = document.getElementById('iframe_a');
if (el.attachEvent) {
el.attachEvent('onload',foo);
} else {
el.onload = foo;
}
}
And if you use an onload attribute in the markup, you don't need to add the listener using script.
It works :)
tested on IE8, ff, chrome
var iframe = document.getElementById('iframeid');
if (iframe .attachEvent) {
iframe .attachEvent('onload',alert("IE Iframe loaded"));
} else {
iframe .onload = alert("Other than IE Iframe loaded");
}
Just use jquery:
$(iframe).bind( 'load', function(){} );

Categories