javascript function convert into jquery equivalent - javascript

I have a javascript function written as follows which works just fine in Firefox for downloading given txt content.
self.downloadURL = function (url) {
var iframe;
iframe = document.getElementById("hiddenDownloader");
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.display = "none";
document.body.appendChild(iframe);
}
iframe.src = url;
}
but it does n't work fine with IE 9 due to some reasons. So i tried to convert into equivalent jquery because jquery has compatibility with all the browsers.
here is the jquery equivalent of the same function:
self.downloadURL = function (url) {
var iframe;
iframe = $("#hiddenDownloader");
if (iframe === null) {
iframe = $('<iframe></iframe>');
iframe.id = "hiddenDownloader";
$("#hiddenDownloader").css("display", "none");
$(document.body).append(iframe);
}
iframe.src = url;
}
But now it does n't work in both the browsers. Please help letting me know what am i doing wrong.

Your problem is in:
iframe = $('<iframe></iframe>');
iframe.id = "hiddenDownloader";
iframe refers to a jQuery Object not a DOM Node. You will have to use .prop to set the id:
iframe = $('<iframe></iframe>');
iframe.prop('id', "hiddenDownloader");
And also you have the same problem here:
if (iframe === null) {
Where you will need the check the length of iframe:
if (iframe.length === 0) {
And again at iframe.src = url; Maybe you can figure this one out:
iframe.attr('src', url);
But why would you convert vanilla JavaScript to jQuery?

Seems like a strange way to download a file.
In any case, this probably works the same was as the original:
if (!iframe.get(0)) {
...
}
... and the id property as another poster mentions.

iframe = document.getElementById("hiddenDownloader");
iframe = $("#hiddenDownloader");
These lines aren't equivalent. The second one create a jQuery object, so the check for null will never equate to true

This link may help u:
http://www.sitepoint.com/forums/showthread.php?743000-IE9-Iframes-DOCTYPES-and-You
or u can add this to the top:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Replace iframe.src = url; with iframe.attr("src",url + "?"+ Math.random()); to prevent caching issue in IE9.
Replace iframe.id = "hiddenDownloader"; with iframe.attr("id","hiddenDownloader");
Replace if (iframe === null) { with if (iframe.length === 0) {

Try with:
iframe = $("#hiddenDownloader")[0];

Related

HTML JavaScript delay downloading img src until node in DOM

Hi I have markup sent to me from a server and I set it as the innerHTML of a div element for the purpose of traversing the tree, finding image nodes, and changing their src values. Is there a way to prevent the original src value from being downloaded?
Here is what I am doing
function replaceImageSrcsInMarkup(markup) {
var div = document.createElement('div');
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(replaceSrc);
return div.innerHTML;
}
The problem is that in browsers as soon as you do:
var img = document.createElement('img'); img.src = 'someurl.com' the browser fires off a request to someurl.com. Is there a way to prevent this without resorting to parsing the markup myself? If there is in no other way does anyone know a good way of parsing the markup with as little code as possible to accomplish my goal?
I know you are already happy with your solution, but I think it would be worth sharing a safe method for future users.
You can now simply use the DOMParser object to generate an external document from your HTML string, instead of using a div created by your current document as container.
DOMParser specifically avoids the pitfalls mentioned in the question and other threats: no img src download, no JavaScript execution, even in elements attributes.
So in your case you can safely do:
function replaceImageSrcsInMarkup(markup) {
var parser = new DOMParser(),
doc = parser.parseFromString(markup, "text/html");
// Manipulate `doc` as a regular document
var images = doc.getElementsByTagName('img');
for (var i = 0; i < images.length; i += 1) {
replaceSrc(images[i]);
}
return doc.body.innerHTML;
}
Demo: http://jsfiddle.net/94b7gyg9/1/
Note: with your current code, browsers will still try downloading the resource initially specified in your img nodes src attribute, even if you change it before the end of JS execution. Trace network transactions in this demo: http://jsfiddle.net/94b7gyg9/
Rather than append the new markup to the DOM before you change the img sources, create an element, set it's inner HTML, change the source of the images and then finally, append the changed markup to the page.
Here's a fully-worked sample.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
//function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
//function newTxt(txt){return document.createTextNode(txt);}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('goBtn').addEventListener('click', onGoBtnClick, false);
}
var dummyString = "<img src='img/girl.png'/><img src='img/gfx07.jpg'/>";
function onGoBtnClick(evt)
{
var div = newEl('div');
div.innerHTML = dummyString;
var mImgs = allByTag('img', div);
for (var i=0, n=mImgs.length; i<n; i++)
{
mImgs[i].src = "img/murderface.jpg";
}
document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>GO!</button>
</body>
</html>
You could directly parse the markup string using a regex to replace the img src. Searching for all the img src urls in the string and then replacing them with the new url.
var regex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
var imgUrls = [];
while ( m = regex.exec( markup ) ) {
imgUrls.push( m[1] );
}
imgUrls.forEach(function(url) {
markup = markup.replace(url,'new-url');
});
Another solution might be, if you have access to it, to set the all the img src to an empty string, and put the url in in a data-src attribute. Having your markup string look like something like this
markup = '
';
Then setting this markup to your div.innerHTML won't trigger any download from the browser. And you can still parse it using regular DOM selector.
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(function(img){
var oldSrc = img.getAttribute('data-src');
img.setAttribute('src', 'new-url');
});

set a Blob as the "src" of an iframe

The following code work perfectly in Chrome
<script>
function myFunction() {
var blob = new Blob(['<a id="a"><b id="b">hey!</b></a>'], {type : 'text/html'});
var newurl = window.URL.createObjectURL(blob);
document.getElementById("myFrame").src = newurl;
}
</script>
But it is not working with IE. Can some one please tell me what is wrong here.
The iframe "src" also set to the blob as shown below.
<iframe id="myFrame" src="blob:0827B944-D600-410D-8356-96E71F316FE4"></iframe>
Note:
I went on the window.navigator.msSaveOrOpenBlob(newBlob) path as well but no luck so far.
According to http://caniuse.com/#feat=datauri IE 11 has only got partial support for Data URI's. It states support is limited to images and linked resources like CSS or JS, not HTML files.
Non-base64-encoded SVG data URIs need to be uriencoded to work in IE and Firefox as according to this specification.
An example I did for Blob as a source of iFrame and working great with one important CAUTION / WARNING:
const blobContent = new Blob([getIFrameContent()], {type: "text/html"});
var iFrame = document.createElement("iframe");
iFrame.src = URL.createObjectURL(blobContent);
parent.appendChild(iFrame);
iFrame with Blob is not auto redirect protocol, meaning, having <script src="//domain.com/script.js"</script> inside the iframe head or body won't load the JS script at all even on Chrome 61 (current version).
it doesn't know what to do with source "blob" as protocol. this is a BIG warning here.
Solution: This code will solve the issue, it runs mostly for VPAID ads and working for auto-protocol:
function createIFrame(iframeContent) {
let iFrame = document.createElement("iframe");
iFrame.src = "about:blank";
iFrameContainer.innerHTML = ""; // (optional) Totally Clear it if needed
iFrameContainer.appendChild(iFrame);
let iFrameDoc = iFrame.contentWindow && iFrame.contentWindow.document;
if (!iFrameDoc) {
console.log("iFrame security.");
return;
}
iFrameDoc.write(iframeContent);
iFrameDoc.close();
}
I've run into the same problem with IE. However, I've been able to get the download/save as piece working in IE 10+ using filesaver.js.
function onClick(e) {
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"});
saveAs(blob, fileName);
e.preventDefault();
return false;
};
$('#download').click(onClick);
See http://jsfiddle.net/o0wk71n2/ (based on answer by #kol to JavaScript blob filename without link)

Is there a client-side way to detect X-Frame-Options?

Is there any good way to detect when a page isn't going to display in a frame because of the X-Frame-Options header? I know I can request the page serverside and look for the header, but I was curious if the browser has any mechanism for catching this error.
OK, this one is old but still relevant.
Fact:
When an iframe loads a url which is blocked by a X-Frame-Options the loading time is very short.
Hack:
So if the onload occurs immediately I know it's probably a X-Frame-Options issue.
Disclaimer:
This is probably one of the 'hackiest' code I've written, so don't expect much:
var timepast=false;
var iframe = document.createElement("iframe");
iframe.style.cssText = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;";
iframe.src = "http://pix.do"; // This will work
//iframe.src = "http://google.com"; // This won't work
iframe.id = "theFrame";
// If more then 500ms past that means a page is loading inside the iFrame
setTimeout(function() {
timepast = true;
},500);
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
if(timepast) {
console.log("It's PROBABLY OK");
}
else {
console.log("It's PROBABLY NOT OK");
}
});
}
else {
iframe.onload = function(){
if(timepast) {
console.log("It's PROBABLY OK");
}
else {
console.log("It's PROBABLY NOT OK");
}
};
}
document.body.appendChild(iframe);
Disclaimer: this answer I wrote in 2012(Chrome was version ~20 at that time) is outdated and I'll keep it here for historical purposes only. Read and use at your own risk.
Ok, this is a bit old question, but here's what I found out (it's not a complete answer) for Chrome/Chromium.
the way do detect if a frame pointing to a foreign address has loaded is simply to try to access its contentWindow or document.
here's the code I used:
element.innerHTML = '<iframe class="innerPopupIframe" width="100%" height="100%" src="'+href+'"></iframe>';
myframe = $(element).find('iframe');
then, later:
try {
var letstrythis = myframe.contentWindow;
} catch(ex) {
alert('the frame has surely started loading');
}
the fact is, if the X-Frame-Options forbid access, then myFrame.contentWindow will be accessible.
the problem here is what I called "then, later". I haven't figured out yet on what to rely, which event to subsribe to find when is the good time to perform the test.
This is based on #Iftach's answer, but is a slightly less hacky.
It checks to see if iframe.contentWindow.length > 0 which would suggest that the iframe has successfully loaded.
Additionally, it checks to see if the iframe onload event has fired within 5s and alerts that too. This catches failed loading of mixed content (in an albeit hacky manner).
var iframeLoaded = false;
var iframe = document.createElement('iframe');
// ***** SWAP THE `iframe.src` VALUE BELOW FOR DIFFERENT RESULTS ***** //
// iframe.src = "https://davidsimpson.me"; // This will work
iframe.src = "https://google.com"; // This won't work
iframe.id = 'theFrame';
iframe.style.cssText = 'position:fixed; top:40px; left:10px; bottom:10px;'
+ 'right:10px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;';
var iframeOnloadEvent = function () {
iframeLoaded = true;
var consoleDiv = document.getElementById('console');
if (iframe.contentWindow.length > 0) {
consoleDiv.innerHTML = 'āœ” Content window loaded: ' + iframe.src;
consoleDiv.style.cssText = 'color: green;'
} else {
consoleDiv.innerHTML = 'āœ˜ Content window failed to load: ' + iframe.src;
consoleDiv.style.cssText = 'color: red;'
}
}
if (iframe.attachEvent){
iframe.attachEvent('onload', iframeOnloadEvent);
} else {
iframe.onload = iframeOnloadEvent;
}
document.body.appendChild(iframe);
// iframe.onload event doesn't trigger in firefox if loading mixed content (http iframe in https parent) and it is blocked.
setTimeout(function () {
if (iframeLoaded === false) {
console.error('%cāœ˜ iframe failed to load within 5s', 'font-size: 2em;');
consoleDiv.innerHTML = 'āœ˜ iframe failed to load within 5s: ' + iframe.src;
consoleDiv.style.cssText = 'color: red;'
}
}, 5000);
Live demo here - https://jsfiddle.net/dvdsmpsn/7qusz4q3/ - so you can test it in the relevant browsers.
At time of writing, it works on the current version on Chrome, Safari, Opera, Firefox, Vivaldi & Internet Explorer 11. I've not tested it in other browsers.
The only thing I can think of is to proxy an AJAX request for the url, then look at the headers, and if it doesn't have X-Frame-Options, then show it in the iframe. Far from ideal, but better than nothing.
At least in Chrome, you can notice the failure to load because the iframe.onload event doesn't trigger. You could use that as an indicator that the page might not allow iframing.
Online test tools might be useful.
I used https://www.hurl.it/.
you can clearly see the response header.
Look for X-frame-option. if value is deny - It will not display in iframe.
same origin- only from the same domain,
allow- will allow from specific websites.
If you want to try another tool, you can simply google for 'http request test online'.
This is how I had checked for X-Frames-Options for one of my requirements. On load of a JSP page, you can use AJAX to send an asynchronous request to the specific URL as follows:
var request = new XMLHttpRequest();
request.open('GET', <insert_URL_here>, false);
request.send(null);
After this is done, you can read the response headers received as follows:
var headers = request.getAllResponseHeaders();
You can then iterate over this to find out the value of the X-Frames-Options. Once you have the value, you can use it in an appropriate logic.
This can be achieved through
a) Create a new IFrame through CreateElement
b) Set its display as 'none'
c) Load the URL through the src attribute
d) In order to wait for the iframe to load, use the SetTimeOut method to delay a function call (i had delayed the call by 10 sec)
e) In that function, check for the ContentWindow length.
f) if the length > 0, then the url is loaded else URL is not loaded due to X-Frame-Options
Below is the sample code:
function isLoaded(val) {
var elemId = document.getElementById('ctlx');
if (elemId != null)
document.body.removeChild(elemId);
var obj= document.createElement('iframe');
obj.setAttribute("id", "ctlx");
obj.src = val;
obj.style.display = 'none';
document.body.appendChild(obj);
setTimeout(canLoad, 10000);
}
function canLoad() {
//var elemId = document.getElementById('ctl100');
var elemId = document.getElementById('ctlx');
if (elemId.contentWindow.length > 0) {
elemId.style.display = 'inline';
}
else {
elemId.src = '';
elemId.style.display = 'none';
alert('not supported');
}
}

How to get WHOLE content of iframe?

I need to get whole content of iframe from the same domain. Whole content means that I want everything starting from <html> (including), not only <body> content.
Content is modified after load, so I can't get it once again from server.
I belive I've found the best solution:
var document = iframeObject.contentDocument;
var serializer = new XMLSerializer();
var content = serializer.serializeToString(document);
In content we have full iframe content, including DOCTYPE element, which was missing in previous solutions. And in addition this code is very short and clean.
If it is on the same domain, you can just use
iframe.contentWindow.document.documentElement.innerHTML
to get the content of the iframe, except for the <html> and </html> tag, where
iframe = document.getElementById('iframeid');
$('input.test').click(function(){
$('textarea.test').text($('iframe.test').contents());
});
You can get the literal source of any file on the same domain with Ajax, which does not render the html first-
//
function fetchSource(url, callback){
try{
var O= new XMLHttpRequest;
O.open("GET", url, true);
O.onreadystatechange= function(){
if(O.readyState== 4 && O.status== 200){
callback(O.responseText);
}
};
O.send(null);
}
catch(er){}
return url;
}
function printSourceCode(text){
var el= document.createElement('textarea');
el.cols= '80';
el.rows= '20';
el.value= text;
document.body.appendChild(el);
el.focus();
}
fetchSource(location.href, printSourceCode);

how to get selected text from iframe with javascript?

how to get selected text from iframe with javascript ?
var $ifx = $('<iframe src="filename.html" height=200 width=200></iframe>').appendTo(document.body);
$(document.body).bind('click', function(){
var u_sel;
if(window.getSelection){
u_sel = ifx[0].contentWindow.getSelection();
// u_sel.text() InternetExplorer !!
alert(u_sel);
}
});
That should do it, as long as the iframe src is targeting your own domain.
Tested only on FireFox 3.6.7 so far.
function getIframeSelectionText(iframe) {
var win = iframe.contentWindow;
var doc = iframe.contentDocument || win.document;
if (win.getSelection) {
return win.getSelection().toString();
} else if (doc.selection && doc.selection.createRange) {
return doc.selection.createRange().text;
}
}
var iframe = document.getElementById("your_iframe");
alert(getIframeSelectionText(iframe));
As noted by jAndy, this will only work if the iframe document is served from the same domain as the containing document.

Categories

Resources