I have a page that loads with initially just a form within an iframe, something like this:
<iframe id="oIframe" ...src='somePage>'
<form ... />
</iframe>
When you click a button in the form, some javascript is invoked that builds a url and then I want to do the following:
frame.src = 'somePage?listId=1';
This works in IE to "reload" the frame with the new contents.
However, in Safari this does not work.
I have jQuery available, but I don't want to replace the existing iframe because there are events attached to it. I also can not modify the id of the iframe because it is referenced throughout the application.
I have seen some similar issues but no solutions that seem to work well for my exact issue.
Any assistance anyone can provide would be great!
Some browsers don't use "src" when calling the javascript object directly from the javascript hierarchy and others use "location" or "href" instead of "src" to change the url . You should try these two methods to update your iframe with a new url.
To prevent browser cache add a pseudo-random string like a number and timestamp to the url to prevent caching. For example add "new Date().getTime()" to your url.
Some calling examples:
document.getElementById(iframeId).src = url;
or
window.frames[iframeName].location = url;
I recommend the first option using document.getElementById
Also you can force the iframe to reload a page using
document.getElementById(iframeId).reload(true);
So the answer is very simple:
1. put a <div id="container"> </div> on your page
2. when reload needed use following jQuery:
$("#container").empty();
$("#container").append("<iframe src='" + url + "' />");
and that's it.
Of course there is more elegant way of creating DOM with jQuery but this gives the idea of "refreshing" iframe.
Works in FF18, CH24, IE9, O12 (well it's jQuery so it will work almost always :)
I found a better solution (albeit not paticularly eloquent) for this using jQuery.ajax:
jQuery.ajax({
type: 'GET',
url: "/somePage?someparms",
success: function() {
frameObj.src = "/somePage?someparms";
}
});
This forces the DOM to be read within the frame object, and reloads it once the server is ready to respond.
Try this
form.setAttribute('src', 'somePage?listId=1');
Well, I was able to find what appears to be a feasible solution -- it's a work in progress, but this is basically what I ended up doing:
var myFrame = document.getElementById('frame'); // get frame
myFrame.src = url; // set src attribute of original frame
var originalId = myFrame.id; // retain the original id of the frame
var newFrameId = myFrame.id + new Date().getTime(); // create a new id
var newFrame = "<iframe id=\"" + newFrameId + "\"/>"; // iframe string w/ new id
myFrameParent = myFrame.parentElement; // find parent of original iframe
myFrameParent.innerHTML = newFrame; // update innerHTML of parent
document.getElementById(newFrameId).id = originalId; // change id back
I ran into this issue using React, passing the key as props.src solved it
const KeyedIframe = ({children, ...props}) => <iframe key={props.src} { ...props}>
{children}
</iframe>
Related
When I add another window using var w = window.open("", "_blank"); , it shows as URL about:blank and I can write to its body with no problem. but at the end, looking at the sources it only has and there is nothing to work with.
If instead I use existing HTML file,var w = window.open("{some path}/Empy.html", "_blank"); All the $(w.document.body).append(... commands write somewhere else not inside the opened file.
Is there a promise I can use, to start writing to it only after the existing file finished rendering?
this will work in IE to, extended from this answer
function openindex(){
OpenWindow = window.open("http://www.htmlgoodies.com/beyond/javascript/article.php/3471221", "_blank");
myFunction = function(){
alert("hi")
window.document.write("<TITLE>Title Goes Here</TITLE>")
window.document.write("<BODY BGCOLOR=pink>")
window.document.write("<h1>Hello!</h1>")
window.document.write("This text will appear in the window!")
window.document.write("</BODY>")
window.document.write("</HTML>")
window.document.close()
}
OpenWindow[OpenWindow.addEventListener ? 'addEventListener' : 'attachEvent'](
(OpenWindow.attachEvent ? 'on' : '') + 'load', myFunction, false
);
}
in my example i overwrite the entire page since i dont know if it has jQuery nor i tried to target specific element, but that is the way to go.
p.s. the url is just random
I'm evaluating Featherlight lightbox and I'm not able to implement code that satisfies my use case. I need a lightbox that will be used as a report viewer which displays dynamically created content assigned to a JavaScript variable. The value of the string is a valid HMTL5 page.
I've looked at the iframe example, but it depends upon a static iframe being in the DOM. That's not what I need.
I've reviewed this GitHub issue and this jsfiddle and I'm not able to successfully modify the fiddle to display a string.
This is an example of the string I would like to display:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
Is this possible and if so how?
I expect that $.featherlight() will be called manually in response to a button click.
The solution I came up with was to modify the Featherlight source code in 2 places as indicated in this block of code (currently around line 383).
iframe: {
process: function(url) {
var deferred = new $.Deferred();
var $content = $('<iframe/>')
.hide()
.attr('src', url)
.attr('id', this.namespace + '-id') // [KT] 10/31/2016
.css(structure(this, 'iframe'))
.on('load', function() {if ($content.show()) {deferred.resolve($content.show()) } else {deferred.resolve($content)} ; }) // [KT] 10/31/2016
// We can't move an <iframe> and avoid reloading it,
// so let's put it in place ourselves right now:
.appendTo(this.$instance.find('.' + this.namespace + '-content'));
return deferred.promise();
}
},
The id attribute is added to the iframe so content can be added by JavaScript, like this:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
var oIframe = document.getElementById('featherlight-id'); // Featherlight's iframe
var iframeDoc = (oIframe.contentDocument || oIframe.contentWindow.document);
iframeDoc.open();
iframeDoc.write(s);
iframeDoc.close();
This then works:
$.featherlight({iframe: 'about:blank', iframeWidth: '96%' });
The 2nd modification is required so that the url 'about:blank' doesn't raise an error.
I also modified the css so as to get the scroll bars to work as needed.
Edit: the issue with Featherlight not opening an iframe when the url is abount:blank has been fixed as of version 1.5.1.
Edit 2: Using v1.5.1, this works without having to make a modification to Featherlight to add an id to to the iframe:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
$.featherlight({iframe: 'about:blank'});
var $iframe = $('.featherlight iframe');
$iframe.ready(function () {
$iframe.contents().find("body").append(s);
});
The accepted SO answer was used for this solution.
I have seen this question many times, and a lot of the answers seem to suggest the base target="_blank" technique. However, I have used this before in the past; but my current page it does not work. I also don't think it could be best option even if it did work; as I ONLY want the links within the iframe src="" to open in a new window. I am hopping there's a simple solution I can add inline to the page. I have also tried adding an id as below, and using JavaScript, still nada.
<iframe src="mywordpressfeed.html" id="frame1" width="310" height="380"></iframe>
JS
$(document).ready(function(){
$("#frame1").attr("target","_blank");
});
Basically the goal is to when a user sees my wordpress feed within the iframe I have on a static page; once the post title is clicked it loads in a new window - as now it loads within the same iframe so there isn't an increased level of readability.
There is no real solution to this, due to the iFrame tag being developed for the opposite.
//pass the iframe to this iframe getting function
function iframeRef( frameRef ) {
return frameRef.contentWindow ? frameRef.contentWindow.document : frameRef.contentDocument
}
//Get Iframe
var inside = iframeRef( document.getElementById('iframeID') );
//Get all links
var links = inside.getElementsByTagName('a');
//Loop throught links and set their attributes
for (var i = 0 ; i<links.length ; i++){
links[i].setAttribute('target','_blank');
}
//No jQuery needed!
thanks to meder
EDIT
Due to iframe same source restrictions I had to find a website with inner iframe from same source so you can paste this code
//pass the iframe to this iframe getting function
function iframeRef( frameRef ) {
return frameRef.contentWindow ? frameRef.contentWindow.document : frameRef.contentDocument
}
//Get Iframe
var inside = iframeRef( document.getElementById('IFwinEdit_Gadget_247730_3349') );
//Get all links
var links = inside.getElementsByTagName('input');
//Loop throught links and set their attributes
for (var i = 0 ; i<links.length ; i++){
links[i].setAttribute('style','background:red');
}
//No jQuery needed!
to the console in this web site and see the inputs change color
I'm making a Greasemonkey script and would like to open a new tab which will not display a URL but some HTML that is part of the script. So basically I want to do something like this (which is obviously not working):
window.open('<html><head></head><body></body></html>');
or
GM_openInTab('<html><head></head><body></body></html>');
Any hints are welcome!
You can do this:
var newWindow = window.open();
and then do
newWindow.document.write("ohai");
April 2021 Edit: This answer is obsolete now. Chrome banned loading data URIs into the top window, and the iframe solution doesn't work for me in Firefox.
Original answer: If the other answer gives you Error: Permission denied to access property "document", see this question about how to handle same-origin policy problems, or this one.
Or, quick and dirty, use a data URI:
var html = '<html><head></head><body>ohai</body></html>';
var uri = "data:text/html," + encodeURIComponent(html);
var newWindow = window.open(uri);
I am putting this here just in case anyone will need this. I have made a way to solve this problem, i created a little website (https://tampermonkeykostyl.dacoconutnut.repl.co) that you can give html to in the hash! Example: (you might need to middle click the url for it to actually open in new tab)
// get url
var el = document.getElementById("url");
// make html
var HTML = `
<h1>hi</h1>
if you can see this then cool <br>
<i>this should be italic</i> and <b>this should be bold</b>
`;
// insert html after the link to demonstrate
document.body.insertAdjacentHTML("beforeend", HTML); // https://stackoverflow.com/a/51432177/14227520
// set url href
el.href = "https://tampermonkeykostyl.dacoconutnut.repl.co/#" + encodeURI(HTML);
// make it open in new tab
el.target = "_blank";
<a id="url">Click here to display following HTML in a link (see js):</a>
Let's say you have a .html file locally stored. What you can do is this:
var newWindow = window.open();
newWindow.document.location.href = "/path/to/html/file";
I am trying to set the 'src' attribute for an iFrame. It works great on FireFox and Internet Explorer. However, when testing on iPad mobile safari changing the 'src' attribute doesn't do anything.
I have an iFrame that has it's 'src' attribute set in the HTML.
<iframe id="iFrame0" style="margin: 0px; overflow: hidden; padding: 0px; height:80px; width:500px" src='.../loading.gif' frameborder="0"></iframe>
Later on I have some code that tries to change the src
var iFrame0 = YAHOO.util.Dom.get('iFrame0');
YAHOO.util.Event.addListener(iFrame0, 'load', function() { alert('test'); });
MyWebService.GetDynamicUrl('someparam', function(url) {
iFrame0.src = url;
});
Not only does the event not fire, but the content of the URL doesn't change. In my testing I noted that the value iFrame0.src does change to the newly passed in URL, but the content on the page does not change.
I am using YUI, however, to eliminate that as a potential problem in my testing I have also tried to directly access the iFrame via:
document.getElementById('iFrame0').attribute("src") = '..../newurl.gif';
Still doesn't work.
In the end I solved this by dynamically creating the iframe and attaching it to the DOM. I also added a timestamp to the id and src attributes in order ensure no caching is being done (though I'm unsure if that truly is necessary).
var elIFrame = document.createElement("iframe");
var dt = new Date();
elIFrame.src = APP_IMAGEPATH + "/loading.gif?dt=" + dt.getTime();
elIFrame.id = 'newCard2' + dt.getTime();
elIFrame.frameBorder = 0;
elIFrame.scrolling = "no";
elIFrame.style.width = "500px";
elIFrame.style.height = "1.8em";
YAHOO.util.Dom.insertAfter(elIFrame, this.pre + "cardMask");
Are you sure that the variable iFrame0 is actually pointing the iFrame DOM object and not some empty object or other element using the same ID (a DIV for example)? Maybe you could try to check the initial src to see if it's what you expect (i.e. '.../loading.gif').
Try to access the frame with the following:
var frameObj = document.frames ? document.frames['iFrame0'] : document.getElementById('iFrame0'),
frameWin = frameObj.contentWindow || frameObj;
And then try to modify its src:
frameWin.src = '..../newurl.gif';