I have a page that loads an external HTML page into an iFrame. There are two problems I am facing with this:
The iFrame is always a fixed height, but I want it to expand
vertically depending on the height of the content.
The content inside the iFrame can not inherit the CSS styles
attached to the HTML page that contains it. The HTML inside the
iFrame has to have it's own link or separate style sheet.
I could be wrong about either of those points, so if I am, please let me know and then I will continue to use the iFrame.
Otherwise, is there a simple Javascript call that can load an external HTML file into a DIV?
Just to be clear, since it seems some people have misunderstood me:
I am asking how to replace an iframe with a DIV and Javascript in order to get the functionality I mention above. I am not looking for ways to make iFrames behave differently.
(I thought this would be fairly common, but most of the questions and information I've found in this site and on the web seems to be situation specific and asks for additional functionality that I don't need and complicates the issue. However, if I've missed something and this is a duplicate, I wouldn't be offended if this got closed.)
You can make an ajax call to fetch your html page and add it to the div. For example using JQuery:
$.get('yourPage.html', function(data) {
$('#yourDiv').html(data);
});
Read more at: http://api.jquery.com/jQuery.get/
I actually wrote up an answer to a different question, that seems to apply here: https://stackoverflow.com/a/10012302/166661
You've got a server that will return to you information -- you could place this information in an IFRAME... or you can call a JavaScript function to retrieve that information and display it in a location (DIV) you set aside on your page.
Here is a sample HTML page that will retrieve information from the server using AJAX
<html>
<head>
<script type="text/javascript">
function getAreaInfo(id)
{
var infoBox = document.getElementById("infoBox");
if (infoBox == null) return true;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status != 200) alert(xhr.status);
infoBox.innerHTML = xhr.responseText;
};
xhr.open("GET", "info.php?id=" + id, true);
xhr.send(null);
return false;
}
</script>
<style type="text/css">
#infoBox {
border:1px solid #777;
height: 400px;
width: 400px;
}
</style>
</head>
<body onload="">
<p>AJAX Test</p>
<p>Click a link...
Area One
Area Two
Area Three
</p>
<p>Here is where the information will go.</p>
<div id="infoBox"> </div>
</body>
</html>
And here is the info.php that returns the information back to the HTML page:
<?php
$id = $_GET["id"];
echo "You asked for information about area #{$id}. A real application would look something up in a database and format that information using XML or JSON.";
?>
Hope this helps!
#mydiv {
all: initial; /* blocking inheritance for all properties */
}
from How To Isolate a div from public CSS styles?
This solution saved my day.
Use a jQuery plugin to resize the iframe dynamically.
You can't restyle content inside a iframe. What are you planning on using the iframe for? There are often better ways to solve things.
I am asking how to replace an iframe with a DIV and Javascript in order to get the functionality I mention above. I am not looking for ways to make iFrames behave differently.
If you want the functionality mentioned you don't have to replace the iframe. The functionality 2 is easier with an iframe. As for functionality 1, you have two choices:
Put your iframe in a DIV and play with css rules like position absolute and relative plus height at 100%
Add a javascript function to handle the resize event of the window object to resize the iframe
Related
Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?
You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.
Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.
I use the Prototype framework to make it easier:
frame1.$('mydiv').style.border = '1px solid #000000'
or
frame1.$('mydiv').addClassName('withborder')
In short no.
You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.
Yes. Take a look at this other thread for details:
How to apply CSS to iframe?
const cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].contentWindow.document.body.appendChild(cssLink);
// ^frame1 is the #id of the iframe: <iframe id="frame1">
You can retrieve the contents of an iframe first and then use jQuery selectors against them as usual.
$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")
$("#iframe-id").contents().find("img").addClass("fancy-zoom")
$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });
Good Luck!
The quick answer is: No, sorry.
It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.
Use Jquery and wait till the source is loaded,
This is how I have achieved(Used angular interval, you can use javascript setInterval method):
var addCssToIframe = function() {
if ($('#myIframe').contents().find("head") != undefined) {
$('#myIframe')
.contents()
.find("head")
.append(
'<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
$interval.cancel(addCssInterval);
}
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);
Combining the different solutions, this is what worked for me.
$(document).ready(function () {
$('iframe').on('load', function() {
$("iframe").contents().find("#back-link").css("display", "none");
});
});
Apparently it can be done via jQuery:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
https://stackoverflow.com/a/13959836/1625795
probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.
Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine.
The only solution is to fetch the page from the server side code and change the needed CSS.
A sort of hack-ish way of doing things is like Eugene said. I ended up following his code and linking to my custom Css for the page. The problem for me was that, With a twitter timeline you have to do some sidestepping of twitter to override their code a smidgen. Now we have a rolling timeline with our css to it, I.E. Larger font, proper line height and making the scrollbar hidden for heights larger than their limits.
var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary
Just add this and all works well:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
If the iframe comes from another server, you will have CORS ERRORS like:
Uncaught DOMException: Blocked a frame with origin "https://your-site.com" from accessing a cross-origin frame.
Only in the case you have control of both pages, you can use https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage to safely send messages like this:
On you main site(one that loads the iframe):
const iframe = document.querySelector('#frame-id');
iframe.contentWindow.postMessage(/*any variable or object here*/, 'https://iframe-site.example.com');
on the iframe site:
// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
// Do we trust the sender of this message?
if (event.origin !== "http://your-main-site.com")
return;
...
...
});
Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.
References:
Printing content of IFRAME
Accessing and printing HTML source code using PHP or JavaScript
http://www.w3schools.com/js/js_htmldom_html.asp
http://www.w3schools.com/js/js_htmldom_css.asp
I am working on a web widget that can be embedded on 3rd party websites.
Since a lot of content management systems do not allow users to post/execute scripts, I want my widget to show an image instead of JS-generated content if such situation occurs.
<script type="text/javascript">
(function(){var s = document.createElement('script');s.src = '//example.com/file.js';s.async = "async";document.body.appendChild(s);}());
</script>
<img src="//example.com/image.svg?param1=value1" src="" id="my_fallback">
For now I am using the code above. Is there any way to show the image only if the script did not load? The goal is to reduce transfer usage and provide better user experience.
The first line of my widget script is removing #my_fallback, but it is not fast enough - sometimes I can see the image for a second before the actual widget content replaces it.
The only thing I came up with is to delay creation of the image by including something like sleep() in the beginning of my image generator.
EDIT
No, <noscript> won't work here. I do not want to fallback if user has disabled javascript. I want to fallback when a script has not loaded - for any reason, especially if some security mechanism cut off the <script> section.
Use html tag Noscript
<noscript>Your browser does not support JavaScript! or a image here</noscript>
Remember
In HTML 4.01, the tag can only be used inside the element.
In HTML5, the tag can be used both inside and .
Edit : -
add one html tag
<span class="noscript">script is loading.....or put image</span>
inside your script tag
now in your scripts which has to be load add one code like
add this line at the end
$('.noscript').hide();
This is the other way which you can handle the same!
One quick fix is to create a global variable from that script, visible to the window object.Also the image must be hidden. Then, on a main.js script check for that variable. If it exists then run your widget code from there. If it doesnt exist then fadeIn the fallback image.
Heres a demo
The default img is an image 272x178 size and the widget image is an image 300x400 size.
To simulate the action when the script is unavailable, just name the variable myWidgetIsEnabled with a different name so the condition fails.
Here is some code:
// Code goes here
var widget = (function(){
window.myWidgetIsEnabled = true;
return {
init: function(){
var s = document.createElement('script');s.src = 'file.js';s.async = "async";
document.body.appendChild(s);}
}
}());
$(document).ready(function(){
if(window.myWidgetIsEnabled){
widget.init();
}else{
console.log('not enabled, the default behavior');
$('.fallback').fadeIn();
}
})
This might be a long shot but I was wondering if anyone knew if there was a way to detect (with Javascript or JQuery) if an iframes source has changed - ie: if a user changes the page within an iframe.
I want to write something like:
if (iframesource == http://www.site.com/urlA){
do something
}
else if (iframesource == http://www.site.com/urlB){
do something different
}
I already know the src attribute for the iframe element (<iframe src="http://www.site.com">) does not change if the page changes within the site so using JQuery to detect the attribute is out.
would anyone know if this is possible? Any advice would be greatly appreciated! Thanks
OK basically after loads of research I have found out that this only works if the iframe is pointing to a URL within your existing site or server. If you are pointing to another site (say YouTube) it will not work.
The best way to transfer information from one site to another is still with JSON.
You will need to build a javascript function that does a few things:
onload.
obtains src value by element id.
passes this into temp_object
enter recursive function with a set_timeout(100ms) say.
compare temp_object to object.
if true, do something, temp_object = object.
#EDIT -----> anti-sop anti-xss
<html>
<head>
<script type="text/javascript">
function GetIFrameUrl()
{
alert('url = ' + document.frames['frame1'].location.href);
}
</script>
</head>
<body>
Find the iFrame URL
<iframe name="frame1" src="http://www.google.com" width="100%" height="400"></iframe>
</body>
</html>
Getting the current src of an Iframe using JQuery
I'm using the Telerik RadSpell control in one of our touchscreen applications. I've managed to style it just right however the darn thing uses window.alert and window.confirm for prompting the user if they want to keep changes etc.
I want to disable these alerts without having to pull apart and modify the telerik controls.
The issue is that the spellcheck dialog uses an iframe and I can't seem to override the window.confirm function inside the iframe.
Sample Code to test overriding confirm.
<!-- mainpage.htm -->
<html>
<head>
<script type="text/javascript">
window.confirm = function(msg){ alert(msg); }
confirm("Main Page Confirm");
</script>
</head>
<body>
<iframe src="./iframepage.htm" >
</iframe>
</body>
</html>
<!-- iframepage.htm -->
<html>
<head>
<script type="text/javascript">
confirm("iframe confirm");
</script>
</head>
<body>
Some content.
</body>
</html>
Results in
Is it possible to override the javascript in an iframe from the parent? If so how?
I just shared an easier solution in the first forum, which demonstrates how to override the cancelHandler and hide the confirm dialog.
For your convenience I am pasting the solution below:
I would propose an easier way to disable the popup and it is to override the cancelHandler function. To do that follow the steps below:
1) Create a JS file named dialog.js in the root of the web application and populate it with the following function:
Telerik.Web.UI.Spell.SpellDialog.prototype.cancelHandler = function (e) {
if (this._cancel.disabled) {
return $telerik.cancelRawEvent(e);
}
//changes will be applied only if spell handler response is received, text has changed
//and the user confirms
this.closeDialog(this._spellProcessor && this._spellProcessor.textChanged() && true);
return $telerik.cancelRawEvent(e);
}
2) Save the file and set the DialogsScriptFile property of RadSpell to point to this file, e.g.
3) Test the solution.
I hope this helps.
You can get a reference to the innerwindow using javascript IFF the frame is from the same exact domain as the parent.
//Get iframe element by getElementById, frames[0], or whatever way you want
var myFrame = document.getElementById("myFrame");
//Get the window of that frame, overwrite the confirm
myFrame.contentWindow.confirm = function(msg){ alert("I overwrote it! : " + msg); }
You should be able to:
document.getElementById('iframe').contentWindow.confirm = [this is confirm in the iframe];
Perhaps something like this might work nicely for you:
document.getElementById('iframe').contentWindow.confirm = window.confirm;
This would link the confirm of the iframe to the confirm of the parent, which is nice if you already have some handling for confirms in the parent.
Note that you also will want to add some handling for possible undefined objects.
var iframe = document.getElementById('iframe');
//iframe exists
if(iframe){
var iframe_window = document.getElementById('iframe').contentWindow;
//window exists (won't if frame hasn't loaded)
if(iframe_window){
iframe_window.confirm = window.confirm;
}
}
You can take a look at the following resources, which could be helpful for your scenario:
http://www.telerik.com/community/forums/aspnet-ajax/spell/how-do-i-turn-off-the-confirm-dialog.aspx
and
http://www.telerik.com/help/aspnet-ajax/spell-client-check-finished.html
They show how to remove the RadSpell confirm and alert popups.
Best regards,
Rumen
I'm looking for a light weight method for client-side includes of HTML files. In particular, I want to enable client-side includes of publication pages of researchr.org, on third party web pages. For example, I'd like to export a page like
http://researchr.org/profile/eelcovisser/publications
(probably just the publications box of that page.)
Using an iframe it is possible to include HTML pages:
<iframe class="foo" style="height: 50em;" width="100%" frameborder="0"
src="http://researchr.org/profile/eelcovisser/publications">
</iframe>
However, iframes require specification of a fixed height, while the pages I'm exporting don't have a fixed height. The result has an ugly scrollbar:
http://swerl.tudelft.nl/bin/view/EelcoVisser/PublicationsResearchr
I found one reference to a method that appears to be appealing
http://www.webdeveloper.com/forum/archive/index.php/t-26436.html
It uses an iframe to import the html, and then a javascript call from the included document to a function defined in the including document, which places the contents of the body of the included file in a div of the including file. This does not work in my scenario, probably due to the same origin policy for javascript, i.e. the including and included page are not from the same domain (which is the whole point).
Any ideas for solving this? Which could be either:
a CSS trick to make the height of the iframe flexible
a javascript technique to lift the contents of the iframe to a div in the including page
some other approach I've overlooked
Requirement: the code to include on should be minimal.
No. The same-origin policy prevents you from doing any of that stuff (and rightly). You will have to go server-side, have a script on your server access that page and copy its contents into your own page (prefeably at build-time/in the background; you could do it at access-time or via AJAX but that would involve a lot of scraping traffic between your server and theirs, which may not be appreciated.
Or just put up with the scrollbar or make the iframe very tall.
As far as I know there is no CSS trick, the only way is to query the iFrame's document.documentElement.offsetHeight or scrollHeight, depending on which is higher, take that value and apply it on the iframe's css height ( add the + 'px' ).
try this ajax with cross domain capability
Why don't you use AJAX?
Try this:
<div id="content"></div>
<script type="text/javascript">
function AJAXObj () {
var obj = null;
if (window.XMLHttpRequest) {
obj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
return obj;
}
var retriever = new AJAXObj();
function getContent(url)
{
if (retriever != null) {
retriever.open('GET', url, true);
retriever.onreadystatechange = function() {
if (retriever.readyState == 4) {
document.getElementsById('content').innerHTML(retriever.responseText);
}
}
retriever.send(null);
}
}
getContent('http://researchr.org/profile/eelcovisser/publications');
</script>
And then, you can parse the received page content with JS with regular expressions, extracting whatever content you want from that page.
Edit:
Sorry, I guess I missed the fact that it's a different domain. But as ceejayoz said, you could use a proxy for that.
If you're using jQuery, you can use the load method to retrieve a page via AJAX, optionally scrape content from it, and inject it into an existing element. The only problem is that it requires JavaScript.