I have looked through certain resources on the stack over flows but some doesn't have answer nor they are inactive.
I will want to autoplay a twitter video when some arrives on my website.
Currently It looks like this:
I was able to do Youtube, so believe this should be possible also?
The twitter widget script seems to inject the player after clicking the image into an iframe
, but the link to click is... embedded in an iframe
. So when you see on your screen the "player" to click, it is in fact not the player but just a link to activate the injection of the player.
So your goal is to activate this injection by the following steps:
set up a target listener for the widget factory
get the widget element, once it's added to the DOM (but after it has been altered by the widget factory)
get it's iframe document's link that triggers the embedding of the player
Prepare your page according to the following documentation:
<div id="videoTarget"></div>
<!--<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>-->
<script>
window.twttr = (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
</script>
Our factory target will be the videoTarget
. This is the place, where the iframe with the video injection link will be placed.
First wait for the twttr
to be ready. Read more in this in the scripting events.
Then use the factory function to create your video.
Once it's loaded, you can use jQuery to find the iframe
content's link, that triggers the injection.
Code:
window.twttr.ready(function(_twttr) {
_twttr.widgets.createVideo(
'560070183650213889',
$('#videoTarget').get(0), {
lang: "en",
}
)
.then(function(el) {
const dataId = $(el).attr('data-tweet-id');
const doc = $('iframe').get(0).contentWindow.document;
const link = $(doc).find("a[href*=" + dataId + "]")[0];
link.click();
});
});
Working solution: https://jsfiddle.net/5qmh1Lpn/121/
Twitters video embed lacks of proper ways to do autoplay. However, it is IMHO an antifeature and it should be the user's decision, wether to play a video or not.
The solution is only a hack and may not work on all browsers in all situations.
Please create a fork, if you want to extend the fiddle to your needs.
Edit: Just for your interest, I found a hidden link with cookie consent in this code, which basically breaks down to "if you click this you agree to our policies" which is very strange, since nobody can't see this message as it's hidden.
https://stackoverflow.com/a/2893315/3098783
https://stackoverflow.com/a/303961/3098783
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With