Read iFrame content with Jquery (iFrame loads more ajax in itself) - javascript

I have a video player I implement with an iFrame.
<iframe
src="//player.twitch.tv/?video=v209807471&autoplay=true&time=02h59m45s"
frameborder="0"
scrolling="no"
allowfullscreen="true"
id="tFrame"
class="ls-vod-iframe"
>
</iframe>
I would now like to read the current timestamp which is located in the .player-seek__time span inside this iframe.
When I check the source code of //player.twitch.tv/?video=v209807471&autoplay=true&time=02h59m45s if shows me an empty div of #video-playback so I assume it loads the contents in another call internally.
I tried it with this:
var $playerBody = $('#tFrame').contents().find('#video-playback');
var $ts = $playerBody.find('.player-seek__time');
console.log($ts);
but $ts.length is 0.
Is there another way to get the content of .player-seek__time or is anything wrong with the above code in general?

getTimeStamp = function() {
var frameDoc = document.getElementById('tFrame').contentDocument;
if (frameDoc) {
return frameDoc.body.querySelector('#video-playback > .player-seek__time').textContent;
}
else {
return false; //maybe access is blocked by the website
}
}
document.getElementById('tFrame').addEventListener('load', function() {
alert(getTimeStamp());
});
<iframe
src="//player.twitch.tv/?video=v209807471&autoplay=true&time=02h59m45s"
frameborder="0"
scrolling="no"
allowfullscreen="true"
id="tFrame"
class="ls-vod-iframe"
>
</iframe>
This should work in general but it seems that twitch won't allow you to load their site inside an iframe?
Also same-origin-policy could prevent an access.
For me it only works when using this code via the console inside a tab.

Related

Remove id from iframe

I have an iframe of a certain page from a site that I'm using, but I don't want all the parts of that page to be displayed with the iframe. Particularly, there's a navigation sidebar on the page that I don't want to be in the iframe. I'm trying to achieve this with the javascript seen below, but I can't quite figure it out.
<iframe width="800" height="800" src="scores/new?site_id=193">
<script>
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
</script>
</iframe>
For security reasons you can't run javascript through iframes. There are some exceptions if you're on the same domain but for the most part you should really avoid it.
If the iframe isn't a site you can control then there's pretty much nothing you can do. If you do control the other site and it's a different domain you might be able to work with the postMessage functions.
Edit: Check out the docs that Mozilla has up here https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
You'd need to create a listener on the inside that handles a message and hides your sidebar. Then on the parent send a message to the iframe to trigger that function.
Parent:
var iframe = document.getElementById('#iframeID');
iframe.contentWindow.postMessage('iframeTrigger');
Iframe:
window.addEventListener('iframeTrigger', hideSidebar);
function hideSidebar() {
//do stuff
}
You can insert a control in the iframed page
//inside the iframed page
var iframe = (function() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
})();
if(iframe === true) {
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
}
Hope this could suit your need.
This should work theoretically, and it works in console. But this doesn't work in the HTML, although you are trying it from the same domain, because of security reasons. I just wanted to tell my view and I tried this:
<iframe src="http://output.jsbin.com/figujeyiyo" frameborder="0" id="ifrm">
Sorry, iframes not supported.
</iframe>
<script>
console.log(document.getElementById("ifrm").contentDocument.documentElement.getElementsByTagName("div"));
e = document.getElementById("ifrm").contentDocument.documentElement.getElementsByTagName("div")[0];
console.log(e);
e.parentNode.removeChild(element);
</script>
You need to execute the code when the page loads, you can do it like this:
document.addEventListener('DOMContentLoaded', function() {
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
});

Random iframe on page load

I have a few iframes on my homepage at the bottom (http://www.binarycontrast.com), where one is randomly selected on page load. The code I'm using below works, but the iframes load really slowly. What the code does is generate a random iframe to display on page load. I actually got the code from another question on here regarding loading random images on page load, and I just tweeked it to what I needed.
If I have a single iframe on the page it loads really quickly, but for some reason using this code slows it down a lot, so I want a way to speed up the iframe loading time whilst using some script to randomly choose one to display.
An alternative method or help with the code I have would be really appreciated.
Please see the below code:
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/24Option" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/OptionFair" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/StockPair" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
And the script used to make it work:
$(window).load(function(){
var divs = $("iframe.random-iframe").get().sort(function(){
return Math.round(Math.random())-0.5; //random so we get the right +/- combo
}).slice(0,1)
$(divs).appendTo(divs[0].parentNode).show();
});
And the css:
iframe.random-iframe { display: none; }
Thanks for any help in advance.
I think the Problem ist that you load all the iframes.
Even the ones you don't need.
You should only hold your Urls (Not the whole iframe tags) and the make a random select for one of the urls.
Only then create a Iframe tag with the selected url.
something like this:
function getRandomUrl(urls) {
var minIndex = 0;
var maxIndex = urls.length - 1;
var randomIndex = Math.floor(Math.random() * (maxIndex - minIndex)) + minIndex;
return urls[randomIndex];
}
var urls = [
"url1",
"url2",
"url3"];
var randomSelectedUrl = getRandomUrl(urls);
$("#hereComesTheIframeInto").html(
"<iframe class='random-iframe' src='" + randomSelectedUrl + "' width='100%' height='700' frameborder='0' scrolling='yes' seamless='seamless'></iframe>");
<div id="hereComesTheIframeInto"></div>
I Hope you get the point. I didn't finish it completely for you.
EDIT:
eradicated error. (I have composed the strings with "&" before but in Javascript you have to do this with "+")
Sorry for this. =(
Instead of loading all the iframes, and then hiding some of them, try to generate only one iframe.
Use random to chose which url will be in the src.
Then use
var chosenURL = 'url'; // The url you randomly chose
var parentNode = 'iframe-container'; // Where you want to put your iframe
$('<iframe class="random-iframe" src="'+chosenURL+'" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>').appendTo(parentNode);
You would be far better of using your code to insert one of three urls randomly into the iframes src.
Looks like there are two issues:
You're hiding the iframes but they're all still loading in the background. You could try using an array with the sources and just creating a single iframe element, or leaving the src tag blank until you're ready to load it.
You're waiting for the window to load, including all images and iframes, before showing any iframe. If you changed the code to run when the document is ready then the code will run much sooner. Better yet, as long as the script is placed after the iframes in the DOM, you don't even need to wait for the whole document to load.
function loadRandomIFrame() {
var divs = document.querySelectorAll(".random-iframe"),
div = divs[Math.round(Math.random() * (divs.length - 1))],
frame = document.createElement("iframe");
frame.width = "100%";
frame.height = 700;
frame.frameborder = 0;
frame.scrolling = "yes";
frame.seamless = "seamless";
frame.src = div.dataset.src;
div.parentNode.appendChild(frame);
}
loadRandomIFrame();
<div class="random-iframe" data-src="http://www.binarycontrast.com/visit/24Option"></div>
<div class="random-iframe" data-src="http://www.binarycontrast.com/visit/OptionFair"></div>
<div class="random-iframe" data-src="http://www.binarycontrast.com/visit/StockPair"></div>

javascript frame navigation in ie11 with a pdf

I have a simple web page where 1 frame displays a pdf and another a menu bar.
<iframe src="bar.html" name="menu" ></iframe>
<iframe src="doc.pdf" name="itempane" ></iframe>
Using chrome I can navigate from the menu bar to the parent and back down to the frame containing the pdf in order to print it
var pWindow = window.parent;
pWindow['itempane'].print();
Attempting to do the same in IE11 gives an Invalid calling object error.
you can see this at http://www.abhrdev.co.uk/main.html
What am I doing wrong / what is IE doing differently?
Cheers
Updated.....
I think I have proved that this is not a javascript coding issue but related to the pdf handling in IE. With the following page
Print PDF<br/>
Print HTML
<iframe src="bar_1.html" name="menu" ></iframe>
<iframe src="doc.pdf" name="pdfpane" ></iframe>
<iframe src="doc.html" name="htmlpane" ></iframe>
and this function
function printFromMain(paneName) {
var pWindow = window[paneName];
pWindow.focus();
pWindow.print();
}
the printing of the html page works but not the pdf the pWindow.focus() gives Invalid Calling Object - any insight into why that might be greatfully recieved
After trying several things, I finally go this to work in IE11:
1) use an object tag instead of iframe
2) run focus() / print() directly on the element
3) run after a timeout, to make sure everything in is loaded. There may be a better way (like using some event listener) to do this, as the timeout time needs to be fairly long for it to work properly
setTimeout(function () {
var contentThingy = document.getElementById('itempane');
contentThingy.focus();
contentThingy.print();
}, 4000);
Object (with a specified id) instead of iframe:
<object id="itempane" ... ></object>
Note: doesn't work in chrome. One of the other variations in the other answers (i.e. using ContentWindow) may.
Try actually using the window.frames to get the frameList and reference it by the frame name that way.
var pWindow = window.parent; //reference the parent from the iframe
var ifr = pWindow.frames.itempane; //get the pdf frame from the frame list
ifr.focus();
ifr.print();
Try this
<iframe src="bar.html" name="menu" ></iframe>
<iframe src="doc.pdf" ID="itempane" ></iframe>
var otherPane = parent.document.getElementById("itempane");
otherPane.focus(); // OR
otherPane.print(); // OR
var doc = otherPane.contentWindow || otherPane.contentDocument;
doc.focus();
doc.print();

How to Grab all contents inside Iframe?

what i need to do is that i want a Pdf of a book that is on google books.
each page of a book is coming through AJAX. but google provides iframe too
this is iframe of one i am looking for
<iframe id="iframeId" frameborder="0" scrolling="no" style="border:0px" src="http://books.google.com.pk/books?id=KOrTwnwcJ9IC&lpg=PP1&dq=magento%20books&pg=PT36&output=embed" width=500 height=500></iframe>
i want to grabe all the contents of this book put it in some div and than make a Pdf of it.i can do all but i just can't grab the contents
i tried this but saying id is not defined
<Script type="text/javascript">
var doc;
if (document.getElementById(iframeId).contentDocument) {
doc = document.getElementById(iframeId).contentDocument;
}
else if (document.getElementById(iframeId).contentWindow) { // older IE
doc = document.getElementById(iframeId).contentWindow.document
}
if (doc) { alert(doc.body.innerHTML) }
</script>
in orignal iframe tag there was not id so than i manually write id for iframe tag that is id="iframeId"
but not working any idea ??
As long as the page loaded in the iframe is in the same domain you can have something like:
var myIFrame = document.getElementById(iFrameName);
var content = myIFrame.contentWindow.document.body.innerHTML;
But Google also provides support for retrieveng info from google docs in JSON format:
https://developers.google.com/gdata/samples/spreadsheet_sample?hl=ro
And the second might be what you are looking for.

Remove current iframe

I have an HTML page that opens an IFRAME ... But at some point, after some user interactions with the IFRAME, it should close itself. I've tried various commands such as:
var fram = $("IFRAME_NAME");
fram.parentNode.removeChild(fram);
this.remove();
this.style.display='none';
var frame = parent.frames['IFRAME_NAME'];
frame.remove();
frame.html("");
document.IFRAME_NAME.document.body.innerHTML = '';
Thanks.
Considering markup like this:
<iframe id="myframe" />
The following jQuery code will remove it in the host page:
$("#myframe").remove();
To close the iframe from within iframe itself, define the function in the host page:
function closeFrame() {
$("#myframe").remove();
}
Then in the code running in the iframe, call:
parent.closeFrame();
If you are using jQuery (and I've understood your question properly), you can use a code as simple as:
<iframe src="http://www.google.com" id="testframe"></iframe>
<script>
$(document).ready(function() {
setTimeout(function () {
$('#testframe').remove();
},5000);
});
</script>
http://jsfiddle.net/pYHx5/

Categories

Resources