Reputation: 141
I have an input function that accepts an iframe embed URL from the user is there any way to get the src from the input. For example: if user inputted <iframe width="1263" height="480" src="https://www.youtube.com/embed/KWFKabzKSxw" title="YouTube video player" frameborder="0" allowfullscreen></iframe>
i want to extract the src that would be https://www.youtube.com/embed/KWFKabzKSxw
and assign it to a new var. My current code is attached below. Any help is appreciated. Thanks in advance.
function input() {
globalThis.urlInput = "";
urlInput = prompt("Enter embed URL:");
if (urlInput == "") {
alert("No URL Inputted");
} else {
rename();
}
}
/*something like this but this wont work because urlInput is not an Id*/
function rename() {
var newUrl = document.getElementById(urlInput).src;
}
<button onclick="input()">Input1</button>
Upvotes: 2
Views: 404
Reputation: 16311
Just convert the input text to html using the DOMParser() API, retrieve the src
from it and then assign the url to a variable say, x
like this:
function input() {
globalThis.urlInput = "";
urlInput = prompt("Enter embed URL:");
if (urlInput == "") {
alert("No URL Inputted");
} else {
rename();
}
}
function rename() {
const parser = new DOMParser();
const x = parser.parseFromString(urlInput, "text/html").body.firstChild.src; //convert the retrieved input text to HTML and retrieve the src attribute value from it
alert(x);
}
<button onclick="input()">Input1</button>
Upvotes: 1
Reputation: 1972
I have created a hidden DOM and added into body and get the URL and delete the DOM after saving the src from Iframe from prompt.
function input() {
globalThis.urlInput = "";
urlInput = prompt("Enter embed URL:");
if (urlInput == "") {
alert("No URL Inputted");
} else {
rename();
}
}
/*something like this but this wont work because urlInput is not an Id*/
function rename() {
var input = document.createElement('div');
input.style.display = 'hidden';
input.id = 'tempInput'
document.body.appendChild(input);
input.innerHTML = urlInput;
var URL = document.querySelector('#tempInput iframe').src;
console.log(document.querySelector('#tempInput iframe').src);
document.getElementById("tempInput").remove();
}
<button onclick="input()">Input1</button>
Upvotes: 1
Reputation: 1216
function input() {
globalThis.urlInput = "";
urlInput = prompt("Enter embed URL:");
$('#input').html(urlInput);
$('#input').hide();
console.log($('#input iframe').attr('src'));
if (urlInput == "") {
alert("No URL Inputted");
} else {
rename();
}
}
/*something like this but this wont work because urlInput is not an Id*/
function rename() {
//var newUrl = document.getElementById(urlInput).src;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="input()">Input1</button>
<div id=input type="hidden"></div>
Upvotes: 1