PrimuS
PrimuS

Reputation: 2683

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

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?

Upvotes: 0

Views: 59

Answers (1)

user9104335
user9104335

Reputation:

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.

Upvotes: 1

Related Questions