I want an iframe to initially have src as blank and then once the page loads; call a JS function and then set the src value to an actual one..
So is <iframe src="#" /> valid OR do I need to use something else like javascript:;, etc
just <iframe src='about:blank'></iframe>
The HTML 5 working draft, section 4.8.2, says (emphasis mine):
The src attribute gives the address of
a page that the nested browsing
context is to contain. The attribute,
if present, must be a valid non-empty
URL potentially surrounded by spaces.
According to RFC 3986, valid URLs must begin with a scheme name, and relative references cannot only consist in a fragment.
Therefore, # is not a valid URL, and should not be used as the value of the src attribute.
Use about:blank instead.
No, it is not valid to specify an empty iframe src.
You should use <iframe src="about:blank" />.
# is meant to be a reference to an anchor within the current page (or, often used as a routing scheme when working with AJAX requests). Using it as the source of an iframe would be senseless, since an iframe does not reference content on the current page and is not used with AJAX requests.
about:blank is a cross-browser standard to display a blank document.
Update June 8th 2012:
It seems that the 'living' spec no longer renders an iframe invalid if the src attribute is missing:
If, when the element is created, the srcdoc attribute is not set, and
the src attribute is either also not set or set but its value cannot
be resolved, the browsing context will remain at the initial
about:blank page.
If both of these attributes, however, are not set, the browsing context will default to about:blank. To provide proper backwards compatibility, it's recommendable to be verbose and, for now, provide the about:blank URL.
It looks like you can also leave out the src completely:
http://dev.w3.org/html5/spec/Overview.html#the-iframe-element
If, when the element is created, the srcdoc attribute is not set, and
the src attribute is either also not set or set but its value cannot
be resolved, the browsing context will remain at the initial
about:blank page.
If you don't want to use about:blank you may use javascript as an src for your iframe like the following example:
<iframe name="TV" id="tv" style="width:100%; background: #800000" src="javascript:document.write('<h3>Results Window</h3>')"></iframe>
The above example will initialize an iframe with maroon background that has a simple message <h3>Results Window</h3>. However, the targets of your links should equals the iframe name attribute i.e in that example TV.
Notice:
Some external website may block requesting their pages from another origin. Try to change the URLs of the hyperlinks in the example below to yahoo.com or google.com, for example, and checkout your browser's console.
Jsbin example
You can use about:blank in the src attribute (as mentioned by ariel earlier), otherwise it would throw an error when serving from a secure page.
A secure page https would throw an error of possibly un-secure data on the secure website.
You could try adding the iframe through Javascript, so you wouldn't need to have a blank one in the HTML:
(jQuery example)
<script type="text/javascript">
$().ready(function() {
$("<iframe />").attr("src", "http://www.bbc.co.uk/").appendTo("body");
});
</script>
Adding the iframe with Javascript allows graceful degradation - users without Javascript won't see a blank iframe.
As part of the about URI scheme standard, about:blank is probably the best option as it has very good browser support.
about:blank Returns a blank HTML document with the media type
text/html and character encoding UTF-8. This is widely used to load
blank pages into browsing contexts, such as iframes within HTML, which
may then be modified by scripts.
You can see further here
For the record
Let's say the next example (Firefox 58 but may be its present in all browsers).
<link href="css.css" rel="stylesheet" type="text/css"/>
<iframe src='about:blank'></iframe>
Iframe is loaded BEFORE the css so the render of the page is visible before the css is loaded. I.e. for a split of a second, the page looks without a css.
Instead:
<link href="css.css" rel="stylesheet" type="text/css"/>
<iframe src='blank.html'></iframe>
It works fine, the css is loaded and the iframe is loaded finally.
if you do call your iframe with
javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(VARİABLES,,true,,false,)
in server side you can again have a src=""
Related
Setting src directly in iframe is working as expected
I'm trying to embed a Sharepoint document here.
For eg
<iframe src="https://rocketlane123-my.sharepoint.com/personal/lokeshkannan_rocketlane123_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc={8822527b-0c56-44f9-8263-40c737db903c}&action=embedview"
width="476px"
height="288px" />
Whereas when I set the src in the script it's failing
<iframe id="x" width="476px" height="288px"></iframe>
<script>
document.getElementById('x').src = "https://rocketlane123-my.sharepoint.com/personal/lokeshkannan_rocketlane123_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc={8822527b-0c56-44f9-8263-40c737db903c}&action=embedview";
</script>
This happens explicitly with SharePoint. So I would like to understand a couple of things here.
1. Am I doing something wrong?
2. Is there any CSP headers which block the parent from adding via JS?
3. Is there any official way from SharePoint to allow this?
3. Is there any way to hack this?
Thanks in advance.
Since this happens across chrome, safari and firefox I think it's not a bug in a specific browser.
Trying this in Firefox yields this error message:
To protect your security, login.microsoftonline.com will not allow
Firefox to display the page if another site has embedded it. To see
this page, you need to open it in a new window.
Opening the console gives this message:
The loading of [url] in a frame is denied by “X-Frame-Options“
directive set to “DENY“.
This is a header that's set by login.microsoft.com to disable embedding the link as an iframe.
This link details this design choice: https://learn.microsoft.com/en-us/sharepoint/troubleshoot/sites/cannot-display-sharepoint-pages-in-iframe
The link mentions you can override the behavior by setting 'AllowFraming', though it doesn't recommend it, as there may be site-breaking changes by embedding it.
A guide to use this feature can be found at this link
The problem is in, javascript amp; should not represent as &.
Change your link to
<body>
<iframe id="x" width="476px" height="288px"></iframe>
<script>
document.getElementById('x').src = "https://rocketlane123.sharepoint.com/sites/MyDocsforSP/_layouts/15/Doc.aspx?sourcedoc={6d327004-5d52-4e42-9707-c964631f8e65}&action=embedview";
</script>
</body>
For the portal I am testing now, I came with the problem that I could not create any xpath locators, after some time I figured out that it was because of an '#document', this cuts the path and makes the simple "copy xpath" to direct the path to a completely different element.
<iframe id="FRAMENAME" src="/webclient/workspace/launch-task/REMbl?ds=BP" width="100%" height="100%" frameborder="0" data-navitemname="navitemname" style="" xpath="1">
#document
<html>
CODE....
</html>
I found the solution for this is it is simply add a switchTo like this:
driver.switchTo().frame("FRAMENAME");
This works and makes the rest of the code to work properly but, takes some extra time processing this command till the code moves to the next line.
So I would like to ask, is there is a better solution for this? something smarter/faster?
I am concerned that when the point where I have lots of scripts comes, the execution time will take too long.
I don't use id locators for example because they are all dynamic so sometimes a xpath is required.
Thank you!
To work with elements inside iframe you must switch to this specific iframe.
Your solution .switchTo().frame("FRAMENAME"); is correct. Selenium does not have any other ways to work with iframe wrappers.
inline frames
As per the documentation in Using inline frames, an inline frame is a construct which embeds a document into an HTML document so that embedded data is displayed inside a subwindow of the browser's window. This does not mean full inclusion and the two documents are independent, and both them are treated as complete documents, instead of treating one as part of the other.
iframe structure and details
Generally, an iframe element is in the form of:
<iframe src="URL" more attributes>
alternative content for browsers which do not
support iframe
</iframe>
Browsers which support iframe display the document referred to by the URL in a subwindow, typically with vertical and/or horizontal scroll bars. Such browsers ignore the content of the iframe element (i.e. everything between the start tag <iframe...> and the end tag </iframe>). Browsers which do not support iframe (or have such support disabled) does the opposite, i.e. process the content as if the <iframe...> and </iframe> tags were not there. Thus, the content matters, despite being ignored by some browsers.
So to summarize, inline frames do not mean an include feature, although it might sometimes serve similar purposes.
Note that, when inline frames are used, the browser (if it supports them) sends a request to the server referred to by the URL in the iframe element, and after getting the requested document displays it inside an inline frame. In this sense inline frames are a joint browser-server issue, but only the browser needs to be specifically iframe-aware; from the server's point of view, there's just a normal HTTP request for a document, and it sends the document without having (or needing) any idea on what the browser is going to do with it.
Something Smarter
As per the best practices while switching to an iframe you need to induce WebDriverWait as follows:
Switch through Frame Name (Java Sample Code):
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("frame_name")));
Switch through iframe XPath (Python Sample Code):
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[#id='ptifrmtgtframe' and #name='TargetContent']")))
Switch through iframe CssSelector (C# Sample Code):
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.CssSelector("iframe#twitter-widget-0")));
Reference
You can find a couple of relevant discussions in:
Python: How can I select a html element no matter what frame it is in in selenium?
Java: Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?
C#: How to wait for a frame to load before locating an element?
tl; dr
Inline frames vs. normal frames
I expect security restrictions (cross-site scripting) will prevent me from doing this, but I thought asking wouldn't hurt. I'm working on a page that may be embedded within another page from a different domain. I don't know anything about the iframe, except I could predict part of the src attribute. I can detect "if" it's embedded, but I really need to know the offset at which it's embedded.
I'm doing some position calculations within my page (that in this case is embedded in an iframe). It works great whether or not it's embedded in all current browsers but gives me problems in IE 7. For some reason the offset jQuery gives me in IE 7 is off by the exact amount of the embedded iframe offset. I could compensate for it in this case, if I could get the offset.
Thanks in advance.
You can do this with JavaScript.
Parent Frame
<html>
<body>
<iframe src="childFrame.html"></iframe>
</body>
</html>
Child Frame
<html>
<body>
Child Frame
</body>
<script type="text/javascript">
alert(document.parentWindow.document.body.innerHTML);
</script>
</html>
The key bit is here "document.parentWindow.document.body". Now you have the parent body you can access the HTML and get any properties you need.
The other way round you can use the Sandbox attribute on the Iframe. Check out the link below. This attribute is not recommended for production code.
http://www.w3schools.com/tags/tag_iframe.asp
Precondition:
I have an aspx-page with iframe inside. This iframe points to the url handled by MVC on the same site (it's hybrid site, both standard ASP.NET and ASP.NET MVC). The resulting page rendered by MVC contains a lot of scripts references.
Problem:
IE9 throws an exception on every single script it load in iframe. These exceptions are similar to this one:
Error: 'Function' is undefined
That is, it says that the most basic things every window has is somehow absent. Once you clicked through all of these popups, the page just works as designed!
If I load a URL from <iframe /> src attribute in the browser directly, everything works as expected.
If I open the page in another browser (I tried Opera, Firefox), everything works as expected -- no errors.
So, what IE9 wants?
There is this msdn page about this bug (or feature).
You get these kinds of errors when you move the iframe element around in DOM. In such cases, IE 9 garbage collects the iframe (causing your undefined bug) and reloads it at another position.
In general, you should create the element, set its src attribute only once and then put it somewhere in the DOM tree once. It has nothing to do with the code which runs in the iframe itself.
I have encountered this same situation in the wild. Basic symptoms:
You load script code in an iframe
The script code runs early (from the head section or top of body)
IE complains about some missing native object
I found that it can often be prevented by delaying the execution of the script code until onload or DOMContentLoaded... Not much help I know but this is one of the most difficult IE scripting bugs I have ever encountered. I upped the score of your question, hope it will be found by others as well and we can get a more detailed answer.
Also see this question:
Error in Internet Explorer 9 (not earlier versions or other browsers) when including jQuery in an iframe
Placing the following script block at the very top of the iFrame html <head> seems to resolve the issue in my case. Basically, it forces the iframe to reload, which as some have pointed out, solves the issue. It seems relatively safe, because, without things like 'Object' and 'Date', javascript is essentially useless.
<script type="text/javascript">
if(typeof(Object)==="undefined"){
window.location.reload();
}
</script>
Try loading the javascript at the end after complete web page is loaded. I feel the script is executing even before the iframe is completely loaded.
for some suggestion of scripting in IE9 view the given link below
http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx
Further investigation revealed that the solution is to add the offending iframe to it's dom location BEFORE setting the 'src' attribute.
Once the 'src' has been set, changing location of the iframe within the DOM stack forces IE9 to garbage collect it.
Once 'src' has been set, iframe can be resized and changed via css positioning, but cannot change the relative location in the DOM stack.
Often times, plugins like dialogs and lightboxes will stuff an iframe with src already set into the dom, then append / prepend or whatever, triggering the GC to take place.
function waitForjQuery(){
if(typeof jQuery!='undefined'){
//Do yor stuff!
}
else{
setTimeout(function(){
waitForjQuery();
},500);
}
}
waitForjQuery();
I would like to create an <iframe> on the page, but then add the src later. If I make an iframe without an src attribute, then it loads the current page in some browsers. What is the correct value to set for the src so that it just loads a blank iframe?
The answers I've seen are:
about:blank
javascript:false
javascript:void(0)
javascript:"";
url to a blank page
Is there a clear winner? If not, what are the tradeoffs?
I'd like to not have mixed content warnings for HTTPS urls, nor any back-button, history, or reload weirdness in all browsers from IE6 onward.
Not sure if all browsers support "about:blank", so I'd just go with your own blank page then.
Another idea: Why not add the whole iframe using javascript instead of just the src?
Standard approach when creating an "empty" iframe (as an iframe shim, for example), is to set the src as javascript:false;. This is the method used by most of the JavaScript libraries that create iframe shims for you (e.g. YUI's Overlay).
What about
about:blank
Re your comment clarifying that you're planning to use the iframe as the target for a form submission:
I would use an empty document on the server that sends back a 204 no content.
It avoids
"mixed content" warnings in IE and HTTPS mode
Unnecessary errors because a client doesn't understand the javascript: protocol
and other exotic shenanigans.
It's also valid HTML.
So what if it generates an extra request? Set the caching headers right, and there will be only one request for each client.
javascript:false:
IE10 and FF (checked in v23 in Linux) will show 'false' as content.
javascript:void(0) && javascript:;:
IE will show 'cannot display the webpage' error in the iframe. Also, when setting the src from a valid url to javascript:void(0), the page will not get blank.
about:blank:
Works in all browsers but IE 9 sends an request to the server with path "null". Still the best bet IMO
Checkout http://jsfiddle.net/eybDj/1
Checkout http://jsfiddle.net/sv_in/gRU3V/ to see how iframe src changes on dynamic updation with JS
javascript:false works in modern browsers.
What I've seen is that this only "fails" when dumb spiders try to load javascript:false as a page.
Solution: Block the dumb spiders.
As I posted in this question: Is an empty iframe src valid?, it looks acceptable to just leave out the src= attribute completely.
IMO: if you don't put the src, your page won't validate. But's about it.
If you put a src="", your server will log many 404 errors.
Nothing is really wrong as in "damaging". But then, is it actually not wrong to use an iframe in itself?
°-
Yes, I know I'm reviving an old thread. Sue me. I'm interested in the answer.
I don't understand why having the trigger being a form submit precludes dynamically creating the IFrame. Does this not do exactly what you want?
<html>
<head>
<script type="text/javascript">
function setIFrame(elemName, target, width, height) {
document.getElementById(elemName).innerHTML="<iframe width="+width+" height="+height+" src='"+target+"'></iframe>";
}
</script>
</head>
<body>
<div id="iframe" style="width:400px; height:200px"></div>
<form onSubmit="setIFrame('iframe', 'http://www.google.com', 400, 200); return false;">
<input type="submit" value="Set IFrame"/>
</form>
</body>
</html>
I run into this line of code:
iframe.setAttribute("src", "javascript:false");
as well. I wanted to remove javascript:URL.
Found this note from the Web Hypertext Application Technology Working Group [Updated 2 October 2019]
[https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-iframe-element][4.8.5_The_iframe_element]
The otherwise steps for iframe or frame elements are as follows:
If the element has no src attribute specified, or its value is the
empty string, let url be the URL "about:blank".