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);
})
}
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 months ago.
I have created a form in Html to post data to a Googlesheets and it is working fine.
When I try to seperate the Javascript file and use it inside html file the script is not working.
What might be the problem and please help me out to solve it.
This is my script.js file:
const scriptURL = 'https://script.google.com/macros/s/AKfycbxRJo4gGwmTHCh6jXO2fcICFJQwI1LwEi7dPI_7vbLq8r4Q-6hbzXprJWIvYn6N7JL_Vw/exec'
const form = document.forms['submit-to-google-sheet']
const msg = document.getElementById("msg")
form.addEventListener('submit', e => {
e.preventDefault();
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => {
msg.innerHTML = "We will get back to you!"
setTimeout(function(){
msg.innerHTML = ""
},5000)
form.reset()
})
.catch(error => console.error('Error!', error.message))
})
I have tried to use it in Html file with the tag:
<script src="script.js"></script>
If I use it inside html file it is properly working. I want to split the script file apart from my html file and not able to perform the functionality even using it from outside or html file with linking it to script file.
If the html and the script file are inside the same directory, try this
<script defer src="./script.js"></script>
defer tells the browser to load the script file only after the html is loaded completely. The ./ before the file name is to specify that the file that you're refereing to(script.js) is on the same directory as the html file.
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;
});
I want to make a site (with HTML, CSS and Javascript) which will scrape data from other sites. I want to use javascript in order to accomplish that. Which is the best way to do it? I would like to avoid using Node.js or some other framework.
If you are getting cors error just use cors anywhere.
For dom parsing use DomParser
Example:
fetch(`https://cors-anywhere.herokuapp.com/${url}`)
.then(response => response.text())
.then(html => {
const parser = new DOMParser()
const dom = parser.parseFromString(htmlContent, 'text/html')
// now you can select elements like for normal node
dom.querySelector('div')
})
Do you have any other problems?
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))
I would like to read file in Java Script.
The best it would be to read line by line, but there is also possibility to read the whole file at once.
Generally on the web there is quite a lot of implementations, but I would like to read a file in very simple way by entering, hardcoded path and file name in the Java Script code, not but any buttons or something like this. The pseudo code below:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var file = FileReader("home/test.txt");//hardcoded path and name of the file
var listOfLines = [];
var line = file.readLine();
while(line != eof) {
listOfLines.push(file.readLine());
file.readLine();
}
</script>
</body>
</html>
Is there such possibility to do something like this.
Thank you.
That would be a pretty big security hole, if your browser could simply read arbityry files from your filesystem. Think, every banner on the web could read configuation files of your OS, and stuff like that.
also check this question/answer: How to set a value to a file input in HTML?
slightly different question, same problem.
But if the client gives your app the file you should process, that's something different.
//use fetch() to get the file content
function fetchFile(file){
const {name, lastModified, size, type} = file;
return fetch(URL.createObjectURL(file))
.then(response => response.text())
.then(text => ({name, lastModified, size, type, text}));
}
//use a FileReader to get the content
function readFile(file){
const {name, lastModified, size, type} = file;
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsText(file);
})
.then(text => ({name, lastModified, size, type, text}));
}
let input = document.querySelector('input');
input.onchange = function(){
const promises = [...input.files].map(fetchFile); //fetch
//const promises = [...input.files].map(readFile); //FileReader
Promise.all(promises)
.then(files => {
console.log(files);
})
}
<input type="file" />
This is just a quick snippet. You'd have to check wether there are further security measures/obstacles due to the fact that a web page is accessing local files; but since this snippet is working, I'm confident that you're good.
FileReader is working well and it is well supported, see:
https://caniuse.com/#search=FileReader
even IE has a partial support.
But it can read ONLY file returned from the user. You cannot read any file with an hardcoded path from the developer. Of course that is for security reasons, the javascript engine in the browser runs in a sandbox.
PS
Also, to read big csv files from javascript, I suggest this library, that I used many times with success:
https://www.papaparse.com/
reference:
https://www.w3.org/TR/FileAPI/
https://www.w3.org/TR/FileAPI/#dfn-filereader
https://developer.mozilla.org/it/docs/Web/API/FileReader