Youtube link src - javascript

I have problem with link to youtube. I get json "https://www.youtube.com/watch?v=kqEfk801E94" and How can I add to src ? I read but this link is incorrect because dont have a embed. Example https://www.youtube.com/embed/kqEfk801E94, don't
https://www.youtube.com/watch?v=kqEfk801E94. How can I do it and replace iframe src?

I'm not sure I understand your question exactly, but I think you want to know what kind of YouTube URL to use in an iframe. If so, the embed works.
If you are writing your own HTML, you can use the embed link in an iframe src directly. This small HTML page loads the URL you linked to:
<!DOCTYPE html>
<html lang="en-gb">
<head>
<title>YouTube Embed</title>
</head>
<body>
<iframe src="https://www.youtube.com/embed/kqEfk801E94" />
</body>
</html>
EDIT: I see you tagged this as Vue.js and JavaScript. If you have an asynchronous response with the embed URL, if you set a local data value, computed property or prop, Vue.js will automatically bind the variable and set it, so you'd only have to do something like:
<template>
<div>
<iframe :src="url" />
</div>
</template>
<script>
export default {
data() {
return {
url: ''
}
},
methods: {
async loadYouTubeUrl() {
const response = await fetch('api/videos/:id/get') // wherever your API is
const json = await response.json()
this.url = json.url // wherever this property is
}
}
}
</script>

I don't know what tools you have available to you to put links into HTML documents from JSON, or the structure of what you're using, but if you can write JavaScript, you can modify the URL link with a regular expression to convert it from a watch to an embed URL, then you can use document.querySelector to find your iframe and then update the src attribute.
This all assumes you have a function that operates after your JSON call. Since I don't know your mechanisms for the JSON, I'll assume you already have the JSON string in a variable called json. Here's an example script:
function getEmbedUrlFrom(json) {
const data = JSON.parse(json)
const url = data.url
const embedUrl = url.replace(/watch\?v=/, 'embed/')
return embedUrl
}
function updateIframeUrl(url) {
const iframe = document.querySelector('iframe')
iframe.src = url
}
updateIframeUrl(getEmbedUrlFrom(json))

Related

How to store the contents of a folder/file to a variable in JavaScript?

I was playing around with the face-api when I ran into what feels like a simple issue: How do I declare a variable as equal to the contents of a local file?
I understand how to navigate a folder for the intended content when doing something such as setting the contents of say an image or script tag in HTML. However, I cant quite discern how to best do this in JavaScript.
For example, lets say I have a folder titled "Images" which contains a file called "beach.jpeg". If I wanted to access the content of said jpeg for future use via something like the face-api how would I make the connection between my file and my JavaScript?
Would it look like the following:
const beachImage = Images/beach.jpeg
I feel like that formatting is missing something to discern that I am intending to access local files as opposed to something else. Thanks for any input! :)
Edit: I forgot to specify that I am running this in a browser and not using node.js. Sorry for not mentioning that.
i assume you running nodejs. you can read contents of a local image this way
const { readFileSync } = require('fs');
const beachImage = readFileSync('Images/beach.jpeg', 'binary'); // put the encoding you need
you might also gonna need a __dirname to build correct path to a file
Edit for html approach. HTML with JS is about triggering and catching events.
Here's an example that has input tag for letting a user choose an image. It displays chosen image. And you can do something with that image in the action function.
<img id="image" src="" width="100" height="100">
<input id="input" name="photo" type="file" accept="image/*">
<button id="action-trigger">Trigger Action</button>
<script>
window.onload = attachEventHandlers;
function attachEventHandlers() {
document.getElementById("input").onchange = handleUploadedImage;
document.getElementById("action-trigger").onclick = action;
}
function handleUploadedImage(event) {
const src = window.URL.createObjectURL(event.target.files[0]);
document.getElementById('image').src = src;
}
function action() {
const image = document.getElementById('image');
if (image.src) {
// do something with image.src
// const detections = await faceapi.detectAllFaces(input) // make sure you imported face-api.js
} else {
alert('Please upload an image first');
}
}
</script>

Import HTML to dynamically add elements using JS

I will be dynamically adding elements to my main index.html using .innerHTML += "<p>example</p>"; However I do not want to store the large html-like string in this .js file, but instead import it from another file example.html
example.html:
<p>example</p>
(It is just a snippet of code and not a standalone html file, but I want to keep the .html extension for linting, autocompletion and general readability)
My attempts:
$(...).load('example.html'): did not work as it replaces of contents of ... with this example instead of appending it
import * from example.html: this and other attempts of importing file failed because of MIME error that text/html cannot be imported
I will be perfectly satisfied with a solution of a method that reads .html as text and returns it as a string (preferably not using AJAX or ES6 as I do not feel confident with them). I would then just use the string in .innerHTML += imported_string; and call it a day.
If I correctly understand what you want to do, you can use FileReader to import the content of a file and convert it to text, for example:
function readFile(event) {
var file = event.target.files[0];
var stream = new FileReader();
stream.onload = function(e) {
var fileContent = e.target.result;
alert(fileContent);
}
stream.readAsText(file);
}
document.getElementById('myFile').addEventListener('change', readFile, false);
<input type="file" accept="html" id="myFile">
The file input is for presentation purposes, you can easily adapt this to your needs.
You should also perform the customary checks, which I ommited for brevity purposes.
Create a fetch request to the file that you want to retrieve. This is, in a basic sense, the same way how a browser would request a html file from the server.
The function below sends a request based on what you input as a file. For example, 'example.html'. It then checks if the request was a success and returns the response as a string. The string can then be appended to your innerHTML.
const getFileAsText = async file => {
const response = await fetch(file);
if (!response.ok) {
throw new Error(`Fetching the HTML file went wrong - ${response.statusText}`);
}
return response.text();
};
You can use it like the example below.
getFileAsText('example.html').then(html => {
document.body.innerHTML += html;
});

Javascript not executed when loading output of XSLTProcessor::transformToDocument() in an Iframe

I'm loading the output (HTMLDocument) of XSLTProcessor::transformToDocument() into an Iframe.
The HTML is properly rendered, but the Javascripts present in the output are not executed / triggered (below is the FF inspector output)
<iframe id="output-frame"></iframe>
#document
<html>
<head></head>
<body onload="console.log('hello')">Hello</body>
</html>
If I reference a static html file instead, it is working fine :
<iframe id="output-frame" src="iframe.html"></iframe>
#document
<html>
<head></head>
<body onload="console.log('hello')">Hello</body>
</html>
Is there a technique to explicitly trigger the inner javascript ?
The issue comes maybe from the technique I'm using to load the HTMLDocument into the Iframe :
var doc = xsltProcessor.transformToDocument(xml);
var frame = document.getElementById("output-frame");
var destDocument = frame.contentDocument;
var srcNode = doc.documentElement;
var newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
I don't really need to use an Iframe, I'm ok to replace the current page with the result of transformToDocument().
I'm testing in FF62.
[update] I have found External JavaScript doesn't work in iFrames? which looks related.
I have tried to specify a same origin src on the iframe (that will be overridden later by my transformation output) but it does not help.
Does someone know how to log "Same-origin" violation/conflict in FF ?
Here's a solution that allows you to set the source of your iframe to any object you want (including HTML documents created by XSLTProcessor::transformToDocument()).
create a Blob object and pass it to URL.createObjectURL(blob)
set your iframe src to the returned url
The browser will fetch the specified resource and handle it like any other. For HTML documents this means that included <script> or <style> elements will be evaluated just as you would expect it.
For your concrete usecase it would look like this:
let xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
let htmlDoc = xsltProcessor.transformToDocument(xml);
let htmlDocStr = new XMLSerializer().serializeToString(htmlDoc);
const getBlobURL = (code, type) => {
const blob = new Blob([code], { type })
return URL.createObjectURL(blob)
}
document.getElementById("my-iframe").src = getBlobURL(htmlDocStr, 'text/html');
Have a look at this blog post for some background information.

Access github html file using JavaScript

I have this html file on github, which I want to access using JavaScript. I tried this, but it didn't work: (I'm using p5.js so the setup function is basically the onload function)
var htmlfile = "[URL THAT POINTS TO HTML FILE]";
function setup() {
console.log(htmlfile.getElementById('id'))
}
Is there any way to do this? Preferably i would like that only plain JavaScript and p5 will be used.
As said in the comments, sending a request to the raw github page will probably be the best way to get the html you want. Here is an example using fetch
document.addEventListener('DOMContentLoaded', getHTML);
function getHTML() {
fetch('https://gist.githubusercontent.com/chrisvfritz/bc010e6ed25b802da7eb/raw/18eaa48addae7e3021f6bcea03b7a6557e3f0132/index.html')
.then((res) => {
return res.text();
})
.then((data) => {
document.write(data);
// get the p tag from the remote html file now we have the html in our document
var firstParagraph = document.getElementsByTagName("p")[0];
console.log(firstParagraph.textContent);
})
}

Simple way to read one image from the JSON URL to HTML

Can someone please advise on a SIMPLEST way to show the email on HTML page from a JSON URL? I tried to run search, but everyone's advise is related to some complicated code that people have. I can read the data from the JSON URL, but I need to know how to instead of the url of the image show the image itself in my page.
JSON file has this location:
{"icon_url":"http://icons.wxug.com/i/c/k/icon.gif"}
if I use this JS format, It just reads the URL data into my HTML site.
document.getElementById('image').innerHTML = something.icon_url;
What would be the simple code, to have this gif actually show as picture on my test website?
There is no need to change the innerHTML attribute. Instead append an image with the DOM API.
//Assuming json_data is a variable containing the JSON in a string format.
json_data = JSON.parse(json_data);
var image = document.createElement("img");
image.onload = function() {
document.getElementById("image").appendChild(image);
}
image.src = json_data.icon_url;
Here's a quick snippet showing this functionality:
//You will probably fetch this not set it manually.
json_data = '{"icon_url": "http://i0.kym-cdn.com/photos/images/original/000/581/296/c09.jpg"}';
json_data = JSON.parse(json_data);
var image = document.createElement("img");
image.onload = function() {
document.getElementById("image").appendChild(image);
}
image.src = json_data.icon_url;
<!DOCTYPE html>
<html>
<body>
<div id="image"></div>
</body>
</html>

Categories