I am trying to adjust the height of an iframe to its content. The iframe will be added dynamically by JavaScript, meaning JavaScript has to deal with the element's properties as well:
let iframe = document.createElement("iframe");
iframe.src = "https://en.wikipedia.org/";
document.getElementById("foo").appendChild(iframe);
iframe.onload = function() {
iframe.style.height = "600px";//<-- Does work, why?
resizeIframe(iframe);//<-- Does not work
//iframe.style.height = iframe.contentWindow.document.body.scrollHeight + "px"; //<-- Does not work (when uncommented)
}
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
<div id="foo">
<!-- Iframe to be inserted in here -->
</div>
JSFiddle
Does anyone happen to know what I could do to make this work? I found the following solution and applied it to the code available above:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
Source
The JavaScript function might (although in this example it would not) work for a plain HTML generated <iframe>, when it comes to a JavaScript generated <iframe>, it does not seem to work. Am I doing something wrong or should I use any alternative method?
Edit: I am using ASP.Net MVC, my project contains the following code in the view:
MyView.cshtml:
<div class="my-class text-center">
<span>
For testing purpose only, this elements has been added. Functionality:
</span>
<br />
<button id="loadiframe" class="btn btn-lg btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
Load iframe
</button>
</div>
When the button is clicked, it should insert/add an iframe element to the .modal-content part of a Bootstrap Modal:
myscript.js:
function foobar() {
let iframe = document.createElement("iframe");
iframe.src = "/home";
$(".modal .modal-content").html(iframe);
iframe.onload = function () {
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
}
}
$(document).ready(function() {
$("button#loadiframe").on("click", function () {
foobar();
});
});
This does seem to add the <iframe>, but not adjust the height. Would anyone happen to know how I could fix this problem? This would be all happening on the same domain as I am referring to the "home" controller which can be found within my project and which is assigned to my <iframe> source attribute (see code above).
Related
I am trying to replace internal links:
<div class="activityinstance">
activity
</div>
to become:
<div class="activityinstance">
<iframe src="http://website.com/hvp/view.php?id=515512">
activity
</iframe>
</div>
I have been able to replace just the text with an iframe using jquery.
https://codepen.io/alanpt/pen/mWJvoB
But this is proving to be quite hard.
Another difficulty is that it needs to only be links with hvp in the address.
I appreciate any help - thanks.
$('body').ready(function(){
$('.activityinstance a').each(function(){ // get all the links inside the .activeinstance elements
var $this = $(this); // ...
var $parent = $this.parent(); // get the parent of the link
var href = $this.attr('href'); // get the href of the link
if(href.indexOf('/hvp/') == -1) return; // if the href doesn't contain '/hvp/' then skip the rest of this function (where the replacement happens)
$this.remove(); // remove the link as I don't see any reasong for it to be inside the iframe
$parent.append('<iframe src="' + href + '"></iframe>'); // add an iframe with the src set to the href to the parent of the link
});
});
A sample of:
<div class="activityinstance">
activity
</div>
[Because of a fact that having HTML inside of an IFRAME tags has no bearing, and is a complete waste of bytes, we will leave it out. And because this solution doesn't need wrappers, we'll stick to the good old (plain and clean) JavaScript].
The snippet:
[].slice.call(document.links).
forEach(
function( a ) {
if( a.href.match(/hvp/) ) {
a.outerHTML = "<iframe src=" + a.href + "><\/iframe>"
}
} );
will result in clean HTML such as:
<div class="activityinstance">
<iframe src="http://website.com/hvp/view.php?id=515512"></iframe>
</div>
...of course, without indentations and unnecessary white-spaces.
$('a').replaceWith(function () {
var content = this;
return $('<iframe src="about:blank;">').one('load', function () {
$(this).contents().find('body').append(content);
});
});
I've an iframe that contain an HTML page.Now I want to get class of the parent item that clicked.
this is my ifram:
<iframe src="//example.com" id="frame" ></iframe>
this is css:
#frame{ width:380px; height:420px;}
this is my script:
$(document).ready(function() {
var iframe = document.getElementById('frame');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document.body;
$(innerDoc).on('click', function(e) {
var thisID = ((e.target).id);
alert(thisID);
alert(innerDoc.getElementById(thisID));
$(thisID).click(function() {
var Allclassnames = $(thisID).parent();
console.log(Allclassnames);
});
});
});
but it return the item was clicked only.how to fix it?
Demo:DEMO
NOTE:these are in a same domain.maybe below DEMO not worked for this reason.but I'm sure that my HTML is inside of the same domain with my web site.
thank you.
Add sandbox attributes to the iframe
<iframe src="/example.html" id="frame" sandbox="allow-scripts allow-same-origin"></iframe>
Change the script to
<script>
$('#frame').load(function() {
$('#frame').contents().on('click', function(e) {
var thisID = ((e.target).id);
alert(thisID);
alert($('#'+thisID,this));
$('#'+thisID,this).click(function() {
var Allclassnames = $(this).parent();
console.log(Allclassnames);
});
});
});
</script>
Make sure that every element in frame doc. have some id or else the alert() may throw an error.
To see the console message of iframe you need to change the scope from the scope dropdown , it's in console tab besides the filter icon in the chrome developer tools.
You cannot interact with the contents of an iframe unless it is on the same domain as the parent document.
See:
https://en.wikipedia.org/wiki/Same-origin_policy
I'm trying to edit the size of dinamic content generated on external url.
There's my code:
HTML:
<div id="movie">
<iframe name="ifr" id="ifr" src="http://zeyu.ucoz.es/directvenvio.html" width="100%" height="480" frameborder="0" scrolling="no"></iframe>
</div>
In this source url, there are 2 scripts, that generate an iframe,
I'm trying to change the width and height of this line:
<script type='text/javascript'>
width=620,
height=382,
channel='zeyudirtc',
g='1';
</script>
This is what i'm trying:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ifr').ready(function(){
$('#ifr').contents().find('script').html('width=960, height=480, channel="zeyudirtc" ');
});
});
</script>
But this doesn't work.
Can help me please?
Thanks in advance.
If you have access to the iframes source, it is possible.
You will have to add Javascript Code to the iframe Content and the surrounding page.
The code you need inside the iframe Content should be like this:
First get the height, the iframe needs.
var height = getDocHeight();
var height = $("html").height();
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if(msie > 0){
height = Math.max(
document.documentElement["clientHeight"],
document.documentElement["scrollHeight"],
document.body["scrollHeight"]
);
}
Then you have to send a message to the surrounding page. Like this:
parent.postMessage(height, "DomainOfTheSurroundingPage");
That's it for the iframe.
On the other site you need to listen to the messages.
if (window.addEventListener) {
window.addEventListener ("message", receiveMessage, false);
} else {
if (window.attachEvent) {
window.attachEvent("onmessage", receiveMessage, false);
}
}
function receiveMessage(event)
{
var height = event.data;
do something();
}
Now you have the height (in px) to work with.
Wrap the iframe in a div.
Div
--- iframe
Then set the height of your wrapper div to 0 and the padding bottom to the height you submitted.
That should do the trick.
If you cannot add the code to the iframe Content however you can't edit the height and width of the iframe dynamically.
Check css "!important" value. In css this is a "high level"
#ifr {
height: 1000px!important;
}
http://jsfiddle.net/mraranturnik/4vqhLdpq/
OK, this is not a problem script or iframe but movi url. In url you have player size. If you want change player size you mast do somthing this
var playerUrl = $('#ifr').contents().find('iframe').attr('src');
Next write RegExp for url and put new src value for iframe in file :)
Your solution change only iframe size not a player size
I am having an iframe inside a div element which is hidden/display none, I want to get the href attribute of a tag using javascript my code is
HTML
<div id="questions" style="display: none;">
<iframe id="article_frame" width="100%" height="100%">
Click here
</iframe>
</div>
JS
window.onload = function() {
alert("Hello " + window.document.getElementById("article_frame"));
}
But I am getting alert as "Hello null" any solution
Thanks
Thanks All,
I have got the answer with javascript it just simple code
var anchor = document.getElementById('en_article_link').firstChild;
var newLink = anchor.getAttribute("href")+"sid="+sidvalue;
anchor.setAttribute("href", newLink);
Ok i feel this may be a slight overkill but it will get you what you require (the href value of the anchor tag inside the iframe) :
window.onload = function() {
var frame = window.document.getElementById("article_frame");
var myString = frame.childNodes[0].textContent
, parser = new DOMParser()
, doc = parser.parseFromString(myString, "text/xml");
var hrefValue = doc.firstChild.getAttribute('href');
alert("Hello " + hrefValue);
}
I guess it depends on your requirements but another way would be to create a string and then using functions: substring and indexof you could get your value. Here is how you would get the string:
window.onload = function() {
var frame = window.document.getElementById("article_frame");
var elementString = frame.childNodes[0].textContent;
//then perform your functions on the string here
}
Note that you can only access the contents of an iframe that contains a page on the same domain due to the Same-Origin Policy (Wikipedia).
I recommend using jQuery for this. The tricks here are:
Wait for the iframe to finish loading $("#article_frame").ready()
Access the iframe's document $("#article_frame").contents()
From there you're just handling the task at hand:
$("#article_frame").ready(function() {
alert("Hello " + $("#article_frame").contents().find("#en_link").href);
});
I have a html page in which there is an image in anchor tag code is :
<img src="images/test.png" />
on body onload event i am calling a javascript function which dynamically changes the image . My code is:
<script type="text/javascript">
function changeImage()
{
document.getElementById('x').innerHTML= '<img src="images/test2.png" />';
}
</script>
This is working fine in firefox but not working in google chrome and ie. Please help..
try this:
<img id="y" src="images/test.png" />
in js
function changingImg(){
document.getElementById("y").src="./images/test2.png"
}
Tested in Chrome and IE.
Then try this: [hoping that id of <a> is available and have at least one img tag]
var x = document.getElementById("x");
var imgs = x.getElementsByTagName("img");
imgs[0].src="./images/img02.jpg";
try following instead of changing innerHTML.
function changeImage()
{
var parent = documeent.getElementById('x');
parent.getElementsByTagName("img")[0].src = "newUrl";
}
As others have indicated, there are many ways to do this. The A element isn't an anchor, it's a link. And no one really uses XHTML on the web so get rid of the XML-style syntax.
If you don't have an id for the image, then consider:
function changeImage(id, src) {
var image;
var el = document.getElementById(id);
if (el) {
image = el.getElementsByTagName('img')[0];
if (image) {
image.src = src;
}
}
}
Then you can use an onload listener:
<body onload="changeImage('x', 'images/test.png');" ...>
or add a script element after the link (say just before the closing body tag) or use some other strategy for running the function after the image is in the document.