How do I put an HTML over Youtube iframe using javascript - youtube-api

How can I access the iframe of a youtube video and use it to layer an html over it? Right now as I access the contentDocument I get a CORS error. Please help if can, below is a code snippet
function onPlayerReady(event) {
var iframe = player.getIframe();
var iframeDocument = iframe.contentDocument;
var pops = document.createElement('div');
pops.innerHTML =
'<div class="bar">' +
'</div>';
iframe.appendChild(pops)
event.target.playVideo();
}

Related

An error occurred please try again later playback id, go to next video?

I have a simple Youtube API code to play videos in a playlist. All of a sudden I start getting the error like: an error occurred please try again later playback id: 2yVtrSo5yT1rs1EY
I did some searching and mainly found solutions for the PC user, like flushing cache/dns etc (I am on a windows laptop by the way).
Question: I was wondering however if it is possible to create a solution for this error(code), in the script in order to make it go to the next song? Or is this only a user based problem? I have an onPlayerError function that just makes the player go to the next song, whatever error occurs. However for the error mentioned above, it does nothing and just shows the error.
<?php
$yt_id='PLFgquLnL59anYA8FwzqNFMp3KMcbKwMaT';
$mymaxcounter = 100;
?>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var numPl = Math.floor((Math.random() * <?php echo $mymaxcounter;?>) + 1);
var playlistId = "<?php echo $yt_id; ?>";
// 3. This function creates an <iframe> (and YouTube player)
function onYouTubeIframeAPIReady() {
player = new YT.Player("player", {
height: '390',
width: '640',
playerVars: {
autoplay: 1,
loop: 1
},
events: {
'onReady': onPlayerReady,
'onError': onPlayerError
}
});
}
// onPlayerReady
function onPlayerReady(event){
//More player vars
player.loadPlaylist( {
listType: 'playlist',
list: playlistId,
index: numPl
} );
//Set shuffle
setTimeout(function() {
player.setShuffle({'shufflePlaylist' : true});
}, 1000);
}
// onPlayerError
function onPlayerError(){
player.nextVideo();
}
</script>

Azure Media Player on iOS devices

I'm streaming O365 videos using Azure Media Player in a web app that must be used only in mobile devices. It works with WP and Android, but the player stuck on iOS.
This is my code
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + bearer);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync($"{url}/GetPlaybackUrl('1')");
var content = await response.Content.ReadAsStringAsync();
var firstVal = JsonConvert.DeserializeObject<VideoToken>(content);
response = await client.GetAsync($"{url}/GetStreamingKeyAccessToken");
content = await response.Content.ReadAsStringAsync();
var secondVal = JsonConvert.DeserializeObject<VideoToken>(content);
Client Side
<video id="newsVideoAMP" class="azuremediaplayer amp-default-skin amp-big-play-centered" tabindex="0"></video>
var initVideoPlayer = function (playbackUrl, streamingKeyAccessToken) {
try {
var myOptions = {
"nativeControlsForTouch": false,
controls: true,
autoplay: false,
techOrder: ["azureHtml5JS", "flashSS", "html5FairPlayHLS", "silverlightSS", "html5"],
logo: { enabled: false }
}
newsVideoPlayer = amp("newsVideoAMP", myOptions,
function () {
this.addEventListener(amp.eventName.error, function () {
window.alert('error');
console.log('Error: amp init');
var errorDetails = newsVideoPlayer.error();
window.alert(errorDetails);
var code = errorDetails.code;
var message = errorDetails.message;
$("#log").append("<li><span>code: " + code + " - detail: " + message + "</span></li>')");
});
});
newsVideoPlayer.src([
{
"src": playbackUrl,
"type": "application/vnd.ms-sstr+xml",
"protectionInfo": [
{
"type": "AES",
"authenticationToken": streamingKeyAccessToken
}
]
}]);
}
catch (err) {
console.log(err);
}
}
I think the issue is related to video encoding. So I tried to use GetPlaybackUrl('0') (and avoid the next token request), but the player stops to work on WP and Android and still not work on iOS.
The logger in callback function doesn't tell me some useful and I have also tried to change the tech order.
Is there a console to manage video encoding in order to avoid the AES algorithm and the decrypt token? Because this doc explain that iOS works with HTML5 tech will no token request. How can I solve? Thanks
I found a workaround to reproduce videos on iOS devices.
Instead of use REST API I put an iframe element in my page with the video embedded.
Like this (using MVC Razor):
var url = "{YourWebsiteUrl}/portals/hub/_layouts/15/VideoEmbedHost.aspx?chId={YourChannelId}&vId={YourVideoId}&width=853&height=480&autoPlay=false&showInfo=false";
<iframe width=853 height=480 id="videoframe" src="#url" allowfullscreen data-spresponsive style='position: absolute; top: 0; left: 0; right: 0; bottom: 0; height: 100%; max-width: 100%;'></iframe>
I get this code from the popup of "embed" menu in the video page of Office365 Video.
If somebody else knows another (and better) method, please let me know. Thanks

Adwords conversion tracking on link clicks that open in a new tab

I want to track the conversion for links in adwords; For this i have the classic code that looks like this(don't worry about values for conversion_id and conversion_label):
<!-- Google Code for Joc Sloturi2 Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = xxxxxxx;
w.google_conversion_label = "dsadsadsadsadadsa";
w.google_conversion_value = dsadasda;
w.google_conversion_currency = "RON";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
window.open(url, '_blank')
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
After that the outbound links are looking like this
Link text whatever
My problem with this is that when I click on the link it opens the link in a new tab and also in the same tab (basically it opens the link twice); Is there a way to only open the link in a new tab in the browser and also track the conversion for it?
I know this is a bit old, but I found a solution. Remove
window.location = url;

How can I confirm a Twitter web intent was sent?

I'd like to confirm a user tweeted after clicking a Twitter Web Intent. How can I accomplish this?
Example:
Tweet
Assuming an anonymous* user clicks this link and tweets, how can I confirm this?
Ideally I'd love to get a link to the tweet.
* anonymous as in not authenticated on my site and without knowing their Twitter username
Update
This solution no longer works after Twitter updated the behaviour of the widgets. You can only track if the tweet button was clicked now, and not if the tweet was actually posted.
You can track tweets using the 'twttr.events.bind' event listener form the Twitter API. A working example of tracking tweets can be found here: http://jsfiddle.net/EZ4wu/3/
HTML:
<i class="icon-twitter-sign icon-white"></i> Tweet
JavaScript:
function reward_user( event ) {
if ( event ) {
alert( 'Tweeted' );
console.log( event );
}
}
window.twttr = (function (d,s,id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
}(document, "script", "twitter-wjs"));
twttr.ready(function (twttr) {
twttr.events.bind('tweet', reward_user);
});
My previous solution is now outdated and no longer appears to work.
Try this:
twttr.events.bind('loaded', function(event) {
window.location = "http://theredirect_link.com"
});
#Niroj's answer no longer works. They updated the api, so the event listener fires immediately after user clicks the button - you have no way of checking if he actually tweeted.
If you create the window yourself (without using Twitter widgets), you can at least detect if the window was closed (either user closed it or tweeted).
Don't link the widgets api!
HTML:
<a id="twitter-intent" href="https://twitter.com/intent/tweet?url=https://www.webniraj.com/2012/09/11/twitter-api-tweet-button-callbacks/&text=Twitter+API:+Tweet+Button+Callbacks"><i class="icon-twitter-sign icon-white"></i> Tweet</a>
JS:
document.getElementById('twitter-intent').addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation(); //this should do in case you don't want to unlink twitter widgets api
var width = 575,
height = 400,
left = (screen.width - width) / 2,
top = (screen.height - height) / 2,
url = this.href,
opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
var win = window.open(url, 'twitter_share', opts);
var timer = setInterval(checkWin, 500);
function checkWin() {
if (win.closed) {
//just assume the user tweeted (he could just close the window without tweeting)
alert("Thank you for tweeting!");
clearInterval(timer);
}
}
});

Pass variable to dialog variable in jQuery Mobile

I have a button that opens up a dialog containing another html file. What I would like to be able to do is pass a variable to the dialog. This is what I have.
var html = "";
var PLAN_ID = '1234';
html += "<div>"
html += 'Final'
html += "</div>"
The PLAN_ID variable is the one that I wish to push to the formFinal.html. I can populate a hidden text input on the dialog with the following code.
$(document).on('pageshow', '#FinalPostPage', function(e) {
var page = $(this);
var query = page.data("url").split("?")[1];
var planid = query.split("=")[1];
$("input[name=Title]",this).val(planid);
})
I can use this but the variable doesn't populate until after the formFinal.html page loads it seems. I need the variable to be used while the page develops. Hope this makes sense.
You could use localStorage to transfer data from this page to the other page.
When you're creating the button, add the PLAN_ID variable as a data-* attribute to the a and also create an id/class for it :
var html = "";
var PLAN_ID = '1234';
html += "<div>"
html += 'Final'
html += "</div>"
Write a click event for the button click :
$(document).on("click", '#dialog-send' ,function(e) {
//prevent default action. we dont want it to redirect. Just yet.
e.preventDefault();
//set item in localStorage.
localStorage["plan_id"] = $(this).data("planid");
//then use changePage to redirect
$.mobile.changePage(this.href, {transition: 'pop', role: 'dialog'});
});
In your pageshow event,
$(document).on('pageshow', '#FinalPostPage', function(e) {
var page = $(this);
//var query = page.data("url").split("?")[1];
//get plan id from localStorage
var planid = localStorage["plan_id"];
$("input[name=Title]",this).val(planid);
});
Hope this helps.

Resources