How can i regex the embed url from a youtube embed HTML? - javascript

I am trying to get just the YouTube embed url from an html embed string.
user puts in an embed-html string to an input. Then i want to strip it down to just the embed link, so i can always have them in my pre-made iframe.
let str = '<iframe width="560" height="315" src="https://www.youtube.com/embed/a24p_KjdpKE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
let indexOfURL = str.indexOf('http');
let embedURL = str.slice(indexOfUrl, str.find(-the-next-double-speech-mark-after-indexOfUrl));
console.log(embedUrl);
Is there a cheeky regex that would do this for me?

Thanks to #VLAZ - i wasn't familiar with HTML parsing before. Not sure why. Anyway, a quick 5-min read on it got me to a point I'd written this, which solves my needs. I hope it solves yours too, if you're reading this. but if it doesn't, i dont overly care.
Note: it works for Vimeo, Soundcloud and YouTube (pasting in their html embed).
const changeEmbedHTMLIntoEmbeddableURL = html => {
let parser = new DOMParser();
let htmlDoc = parser.parseFromString(html, 'text/html');
let embeddableURL = htmlDoc.getElementsByTagName('iframe')[0].src;
console.log('Embeddable URL: ', embeddableURL);
return embeddableURL;
}

Related

I'm using JavaScript & Regex to build objects around links. Need some clarification

To clarify - I've built a comment system that sanitizes all HTML and displays it as plaintext to prevent trolling, cross-site scripting, etc.
On top of that, I have javascript that runs after the page loads, and detects DIRECT links to Youtube and Imgur content, then builds the appropriate player/frame/tag to display that content.
Here is my example code:
<div class="video imgur">
https://i.imgur.com/Ym7MypF.jpg
https://www.youtube.com/watch?v=t-ZRX8984sc
</div>
And script:
$('.video').html(function(i, html) {
return html.replace(/(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="420" height="345" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>');
});
$('.imgur').html(function(i, html) {
return html.replace(/(?:https:\/\/)?(?:i\.)?(?:imgur\.com|)\/(.+)/g, '<img src="https://i.imgur.com/$1">');
});
I can get one to work without the other - however - running both on the same page invariably produces broken tags and links like this, depending on the order:
<iframe width="420" height="345" src="https:<img src=" https:="" i.imgur.com="" www.youtube.com="" embed="" t-zrx8984sc"="" frameborder="0" allowfullscreen=""></iframe>
Why won't my code differentiate between Imgur and Youtube and handle them separately? I'm new at Regex and cannot tell what I'm doing wrong. If anyone could sort me out I'd be grateful.
Your Imgur regex matches too many URLs, e.g.:
https://example.com
https://www.youtube.com/watch?v=foobar
https://imgur.com/foobar
Try using this regex instead: /(?:https:\/\/)?(?:i\.)?(?:imgur\.com)\/(.+)/g

Adding ?enablejsapi=1 to YouTube iframe Code

I have a Wordpress site and I have a custom field which holds YouTube iframe codes. There is a string holding these iframe codes named $embed. Videos are displayed in the theme with code:
<?php print($embed); ?>
I want to convert my standard YouTube embed codes such that:
Standard Youtube Embed Code:
<iframe width="560" height="315" src="https://www.youtube.com/embed/uxpDa-c-4Mc" frameborder="0" allowfullscreen></iframe>
Converted Format:
<iframe width="560" height="315" src="https://www.youtube.com/embed/uxpDa-c-4Mc?enablejsapi=1&html5=1" frameborder="0" allowfullscreen id="video"></iframe>
Simply, I want to add ?enablejsapi=1&html5=1 to end of URL and add id="video".
How can i obtain this iframe code by manipulating the parameter $embed?
Tnx.
This will add the extra params to the source. (Replace with your current print($embed) code.
// use preg_match to find iframe src
preg_match('/src="(.+?)"/', $embed, $matches);
$src = $matches[1];
// add extra params to iframe src
$params = array(
'enablejsapi'=> 1,
'html5' => 1
);
$new_src = add_query_arg($params, $src);
$embed = str_replace($src, $new_src, $embed);
$embed = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $embed);
print($embed);

Replace all instances of YouTube / Vimeo iframe in string

I have a string that might contain one or more instances of a YouTube or Vimeo iframe. I am looking for a javascript function that searches through this string, detects the ID of the video in the iframe src, then replaces the existing instances of the iframe with an iframe wrapped in a div.
So input would be:
<p>Interesting text, great, fantastic.</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/EShfC-uhlv8" frameborder="0" allowfullscreen></iframe>
<p>Another great thing</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/umiN04tPpl0" frameborder="0" allowfullscreen></iframe>
Output:
<p>Interesting text, great, fantastic.</p>
<div class="iframe-container">
<iframe src="https://www.youtube.com/embed/EShfC-uhlv8?html5=1" frameborder="0" allowfullscreen></iframe>
</div>
<p>Another great thing</p>
<div class="iframe-container">
<iframe src="https://www.youtube.com/embed/umiN04tPpl0?html5=1" frameborder="0" allowfullscreen></iframe>
</div>
I have tried wrapping my brain around regexp, even with all the examples around I just can't seem to figure out how to do this.
Anyone have a solution?
Copy/pasting the work I am about to reference directly would get me in trouble, so hopefully an explanation of the methodology would be sufficient. ( If it's not, let me know. )
Assuming you have no idea of the names of the iframes, just plop down a getElementsByTagName(iframe) and then iterate over the resulting array with a loop that gathers all the info from the iframe, which you will use to create a replacement element using innerHTML. This replacement element will have you funky iframe wrapped in whatever you want. Finally, we use replaceChild(replacement, original) and you're set.
For example, here is how I create my replacement element:
var replacement = document.createElement("replacement");
replacement.innerHTML =
"<div class=iframe-container>"
+ "<iframe src=https://www.youtube.com/embed/EShfC-uhlv8?html5=1 frameborder=0 allowfullscreen></iframe>"
+ "</div>"
In simpler terms -- write the code as it would look in the .html file.
Another tricky thing you can do is adding IDs to all the elements and just going through them with getElementById, but it seems like a lot of extra work, unless you're the one developing the page and can just ID-entify the iframes.
Let me know how it goes! If anything is unclear, which would be understandable, considering the format I've written all of this in, just let me know and I will help.
PS: I know a lot of people here don't like innerHTML. They are all pansies.

Why is jquery concatenating string twice?

I'm trying to play an embedded Youtube video after a button click (.playbutton).
The video is embedded as an iframe within a div named #youtubecontainer.
The easiest way to achieve this is to append '?autoplay=1' to the iframe's src attribute. (I know there is an API, but for now I need to do it this way.)
My HTML code is this
<div class="playbutton">
<img class="playicon">
</div>
<div id="youtubecontainer">
<iframe width="560" height="315" src="//www.youtube.com/embed/XeoFLxN5520" frameborder="0" allowfullscreen></iframe>
</div>
Javascript code
$(function() {
//This controls YouTube playback via button
$('.playbutton').click(function() {
$("#youtubecontainer iframe").attr('src', ($("#youtubecontainer iframe").attr('src') + '?autoplay=1'));
});
});
However, this appends'?autoplay=1' to the src twice, so it reads as follows and fails:
<iframe width="560" height="315" src="//www.youtube.com/embed/XeoFLxN5520?autoplay=1?autoplay=1" frameborder="0" allowfullscreen=""></iframe>
Any ideas why?
Try to replace that autoplay before you add it. Because when you second click on it, you are adding again the ?autoplay=1 what has still there before.
Working DEMO
$("#youtubecontainer iframe").attr('src', $("#youtubecontainer iframe").attr('src').replace(/\?autoplay=1/, "") + '?autoplay=1');
You could try to save the original src of the iframe before the click event:
var source;
$(function() {
//This controls YouTube playback via button
source = $("#youtubecontainer iframe").attr('src');
$('.playbutton').click(function() {
$("#youtubecontainer iframe").attr('src', source + '?autoplay=1');
});
});
Working fiddle: http://jsfiddle.net/robertrozas/notjtz3d/1/

How to read webkitAllowFullScreen attribute in iframe using javascript

For the following iframe code:
<iframe src="testA.html" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
Inside testA.html, how do I tell if the webkitAllowFullScreen attribute is included using javascript?
If the allowfullscreen attributes are added to the iframe the variable below should be true
var fullscreenEnabled = document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled;
This even works when the iframe src is on a different domain.
Note: the letter s in fullscreenEnabled is uppercase for Firefox
This is the most robust solution:
if(window.frameElement && window.frameElement.hasAttribute("webkitAllowFullScreen")){
}
It utilizes window.frameElement, which returns the DOM node of the parent framing element, which you can then make a hasAttribute call against.

Categories

Resources