Enforce nocookie mode when using the YouTube iframe API - youtube-iframe-api

I'd like to ensure that when I initialise a new YT.player() that I can set it to make sure that it uses an embed from the www.youtube-nocookie.com domain. Is this currently possible? I haven't been able to find any reference to it in the docs yet.

I know, this is a late answer, but maybe relevant as it's still working:
You can use the host-parameter:
function onYouTubeIframeAPIReady() {
var player = new YT.Player('player', {
videoId: 'aqz-KE-bpKQ',
host: 'https://www.youtube-nocookie.com',
playerVars: {
origin: window.location.host
}
});
}
var s = document.createElement('script');
s.src = 'https://www.youtube.com/iframe_api';
document.head.appendChild(s);
<div id="player"></div>
Sadly, it does not work here on stackoverflow because of the same-origin-policy.
I have the same code running in an active project, though..

Ah. I managed to solve this just as I was about to post my question.
In my code I use something like:
<iframe id="myVideo" src="https://www.youtube-nocookie.com/embed/<VIDEO_ID>?enablejsapi=1"></iframe>
...then I can use the following to get the player that has already been embedded in the HTML via JS:
var player;
var onYouTubeIframeAPIReady = function() {
player = new YT.Player("myVideo");
};
Still, it would be nice if there was a way to initialise a www.youtube-nocookie.com video with JS too.

Related

Google Tag Manger / Inject iframe in DIV / Works in Preview Mode but not in production

I'm trying to insert an iframe into a div with the UTM parameters of the parent URL. In order to achieve this, I have a simple trigger based on page URL like this:
and then for the tag, I have this:
The code is the following, I have removed the iframe url:
​<script type="text/javascript">
console.log('insert iframe');
var iframeurl = 'xxx';
var params = window.location.search.replace('?','');
var thisScript = document.scripts[document.scripts.length - 1];
var iframe = document.createElement('iframe');
iframe.setAttribute('src', iframeurl +'&'+ params);
iframe.setAttribute('width', '100%');
iframe.setAttribute('height', '700px');
iframe.setAttribute('type', 'text/html');
iframe.setAttribute('frameborder', 0);
iframe.setAttribute('allowTransparency', 'true');
iframe.style.border = '0';
getRef = document.getElementById("contest_iframe");
parentDiv = getRef.parentNode;
parentDiv.insertBefore(iframe, getRef);
</script>
When I execute the code in my browser console, it works. When I execute the Tag Assistant it works but when I try it in production, it doesn't work, the tag is not fired.
This is what I see in the assistant:
Everything seems to be ok, I don't understand why it doesn't work, I probably have missed something somewhere.
Do you have any idea?
Thanks
Laurent
Have you tried making it an anonymous, self-executing function?
(function(){
//your code
})();

translate my entire website from Spanish to English, , Google Translate it's no longer available

Good evening, I need help with translating my website from Spanish to English, it is developed in asp.net, my boss requested that I use google translate for ease, but the google translation service seems to be no longer available. Anyone know of a similar library that does the same, that does the automatic translation of my entire website
Google translate sends me this message:
We no longer provide new access to Google Translate's Website Translator. This change does not affect existing use of the Website Translator.
We encourage users looking to translate webpages to use browsers that support translation natively.
Personally I use the deepl API. https://www.deepl.com/de/docs-api/
There are many others that are worth looking at.
First, add this where you want a button to change the language in HTML body.
<div id='google_translate_element'/>
Then add these scripts in your <head> tag of HTML.
<script type='text/javascript'>
function googleTranslateFunction(){
new google.translate.TranslateElement({pageLanguage:'hi', layout:google.translate.TranslateElement.InlineLayout.SIMPLE},'google_translate_element');
} </script>
<script type='text/javascript'>
//<![CDATA[
(function(){var gtConstEvalStartTime = new Date();/*
Copyright The Closure Library Authors.
SPDX-License-Identifier: Apache-2.0
*/
var h=this||self,l=/^[\w+/_-]+[=]{0,2}$/,m=null;
function n(a){
return(a=a.querySelector&&a.querySelector("script[nonce]"))&&(a=a.nonce||a.getAttribute("nonce"))&&l.test(a)?a:""
}
function p(a,b){
function c(){}c.prototype=b.prototype;
a.i=b.prototype;a.prototype=new c;
a.prototype.constructor=a;
a.h=function(g,f,k){
for(var e=Array(arguments.length-2),d=2;
d<arguments.length;d++)e[d-2]=arguments[d];
return b.prototype[f].apply(g,e)
}
}
function q(a){return a};
function r(a){
if(Error.captureStackTrace);
else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))
}
r.prototype.name="CustomError";
function u(a,b){
a=a.split("%s");
for(var c="",g=a.length-1,f=0;
f<g;f++)c+=a[f]+(f<b.length?b[f]:"%s");
r.call(this,c+a[g])
}
p(u,r);
u.prototype.name="AssertionError";
function v(a,b){
throw new u("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));
};
var w;
function x(a,b){this.g=b===y?a:""}x.prototype.toString=function(){return this.g+""};var y={};
function z(a){
var b=document.getElementsByTagName("head")[0];b||(b=document.body.parentNode.appendChild(document.createElement("head")));
b.appendChild(a)
}
function _loadJs(a){
var b=document;
var c="SCRIPT";"application/xhtml+xml"===b.contentType&&(c=c.toLowerCase());
c=b.createElement(c);
c.type="text/javascript";
c.charset="UTF-8";
if(void 0===w){b=null;var g=h.trustedTypes;
if(g&&g.createPolicy){
try{b=g.createPolicy("goog#html",{createScriptURL:q})}
catch(t){h.console&&h.console.error(t.message)}w=b}
else w=b
}
a=(b=w)?b.createScriptURL(a):a;a=new x(a,y);a:{
try{
var f=c&&c.ownerDocument,k=f&&(f.defaultView||f.parentWindow);k=k||h;
if(k.Element&&k.Location){var e=k;break a}}
catch(t){}e=null}
if(e&&"undefined"!=typeof e.HTMLScriptElement&&(!c||!(c instanceof e.HTMLScriptElement)&&(c instanceof e.Location||c instanceof e.Element))){
e=typeof c;
if("object"==e&&null!=c||"function"==e)
try{}
catch(t){}
else d=void 0===c?"undefined":null===c?"null":typeof c;v()
}
a instanceof x&&a.constructor===x?d=a.g:(d=typeof a,v("expected object of type TrustedResourceUrl, got '"+a+"' of type "+("object"!=d?d:a?Array.isArray(a)?"array":d:"null")),d="type_error:TrustedResourceUrl");c.src=d;
(d=c.ownerDocument&&c.ownerDocument.defaultView)&&d!=h?d=n(d.document):(null===m&&(m=n(h.document)),d=m);
d&&c.setAttribute("nonce",d);z(c)
}
function _loadCss(a){
var b=document.createElement("link");
b.type="text/css";b.rel="stylesheet";
b.charset="UTF-8";b.href=a;z(b)
}
function _isNS(a){
a=a.split(".");
for(var b=window,c=0;c<a.length;++c)if(!(b=b[a]))return!1;
return!0
}
function _setupNS(a){
a=a.split(".");
for(var b=window,c=0;c<a.length;++c)b.hasOwnProperty?b.hasOwnProperty(a)?b=b[a]:b=b[a[c]]={}:b=b[a]||(b[a]={});
return b
}
if (_isNS('google.translate.Element')){return}(function(){
var c=_setupNS('google.translate._const');
c._cest = gtConstEvalStartTime;gtConstEvalStartTime = undefined;c._cl='en';
c._cuc='googleTranslateFunction';
c._cac='';c._cam='';c._ctkk='447972.1887378764';
var h='translate.googleapis.com';
var s=(true?'https':window.location.protocol=='https:'?'https':'http')+'://';
var b=s+h;c._pah=h;c._pas=s;c._pbi=b+'/translate_static/img/te_bk.gif';
c._plla=h+'/translate_a/l';c._ps=b+'/translate_static/css/translateelement.css';
c._puh='translate.google.com';
_loadCss(c._ps);_loadJs(b+'/translate_static/js/element/main.js');})();})();
//]]>
</script>
Boom Now your website will successfully change the language with option appers
here is image you can see this is result after you follow

youtube api iframe loadvideobyid starts video where last one left off

I am using youtube api iframe and just getting going with the sample code. When I issue:
player.loadVideoById("ytidNo1") the proper video starts ("ytidNo1" is a valid youtube id)
Then, say, 10 seconds later, if I issue another:
player.loadVideoById("ytidNo2") the 2nd video starts, but it starts at the point where the last one was playing at (eg 10 seconds in).
This is new behavior in the last day or so and I have not changed my code.
To correct the problem, I tried:
player.loadVideoById("ytidNo1",0)
then
player.loadVideoById("ytidNo2",0)
and issue still happens.
Anyone else have or just starting to have this issue?
I also had the same problem. Playing around I eventually got it to work.
I had to use seekTo(0); (see Jim's comments)
More details about the problem.
If the video actually played to the end I didn't need to do anything.
If the video was skipped part way through I had to call
player.seekTo(0);
on the old video before calling loadVideoByID("ytid", 0); on the next video.
I also had to handle the case where after calling loadVideoByID I got an error. (e.g. 150) If I had an error I could not call seekTo because it would cause the next video to play audio only.
hope this helps
I am trying to reproduce the issue using the official sample::
https://developers.google.com/youtube/iframe_api_reference
after the stop I am selecting another video in the same way, and seems to work well:
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<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);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
player.loadVideoById("tYrND5hMY3A");
}
</script>
</body>
</html>​
http://jsfiddle.net/5wxFv/3/

Dynamic loading of stylesheet using YUI3

I am dynamically loading stylesheets using YUI3 'Get'. which is working flawlessly however, as far as I can tell it doesn't give me any way to set id's for these new stylesheets which is causing the stylesheet to be loaded multiple times as the user navigates around the site.
var css_obj = Y.Get.css(location.pathname+"/../css/"+jta["iss"]+".css");
Does anyone have any other way of doing this so that I can test prior to loading the css, if it has already been loaded?
Thanks
Did you try using your own variable to check if it's already been loaded?
var css_obj;
function LoadCss() {
if (css_obj == null) {
css_obj = Y.Get.css(location.pathname+"/../css/"+jta["iss"]+".css");
}
}
and if you're using jQuery you could write
$(document).ready(function(){ LoadCss(); });
I like Hunter's solution. You do have access to the inserted link node, though, and you can set its id if you wish:
http://ericmiraglia.com/yui/demos/cssid.php
YUI().use("get", function(Y) {
Y.Get.css("http://ericmiraglia.com/yui/demos/red.css", {
onSuccess: function(o) {
o.nodes[0].setAttribute("id", "myElementId");
alert(o.nodes[0].getAttribute("id"));
}
});
});

Detecting if YouTube is blocked by company / ISP

We have YouTube videos on a site and want to detect if it is likely that they will not be able to view them due to (mostly likely) company policy or otherwise.
We have two sites:
1) Flex / Flash
2) HTML
I think with Flex I can attempt to download http://youtube.com/crossdomain.xml and if it is valid XML assume the site is available
But with HTML I don't know how to do it. I can't even think of a 'nice hack'.
I like lacker's solution, but yes, it creates a race condition.
This will work and won't create a race contition:
var image = new Image();
image.onload = function(){
// The user can access youtube
};
image.onerror = function(){
// The user can't access youtube
};
image.src = "http://youtube.com/favicon.ico";
You can load an image from youtube using javascript and check its properties. The favicon is tiny and has a consistent url -
var image = new Image();
image.src = "http://youtube.com/favicon.ico";
if (image.height > 0) {
// The user can access youtube
} else {
// The user can't access youtube
}
I think this is slightly better than loading javascript because this won't try to run any code, and while youtube might rename their javascript files, or functions from those files, they are unlikely to ever rename their favicon.
This should work. Basically, it loads a youtube.com javascript file, then checks if a function in that file exists.
<html>
<head>
<script src="http://www.youtube.com/js/account.js"></script>
<script>
function has_you_tube()
{
if(typeof addVideosToQuicklist == 'function')
{
return true;
}
else
{
return false;
}
}
</script>
</head>
<body>
<script>alert( "has_youtube: " + has_you_tube() ); </script>
</body>
</html>
I got stuck on this today and tried the favicon test but it wasnt working in IE. I was using the YouTube Player API Reference for iframe Embeds to embed youtube videos into my site so what I did is perform a check on the player var defined just before the onYouTubeIFrameReady with a delay on the javascript call.
<script> function YouTubeTester() {
if (player == undefined) {
alert("youtube blocked");
}
}
</script>
<script>window.setTimeout("YouTubeTester()", 500);</script>
Seems to work for me. I needed the delay to get it to work in IE.
This worked for me... Its also my first post, hope it helps some one too.
<?php
$v = file_get_contents("https://www.youtube.com/iframe_api");
//Tie counts to a variable
$test = substr_count($v, 'loading');
if ($test > 0)
{ ?>
<iframe>YOUTUBE VIDEO GOES HERE</iframe>
<?php
}
else
{
echo "<br/> no connection";
}
?>

Resources