javascript fetch command does not display the content on the html page - javascript

I have a simple text file in the same directory as HTML file , I used the fetch command in javascript to display the text file content in the page div section when the loading of the page finish
however, my code doesn't work and nothing has been displayed, my question is does the fetch command suitable for such a task or should I use filereader ?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Page</title>
<meta name="generator" >
<style type="text/css">
</style>
<script type="text/javascript" defer>
const myfile=location.href.slice(0,location.href.lastIndexOf("/"))+"/a.txt"
console.log(myfile);
async function getTextFile1() {
try {
const response = await fetch(myfile, { mode: 'no-cors' });
const fileText = await response.text();
//console.log(window.location);
//console.log(window.location.href);
const tagElement = document.getElementById("about_layer");
tagElement.innerText = fileText;
} catch (error) {
console.log(error);
}
}
window.onload = getTextFile1;
</script>
</head>
<body>
<div >should be placed here </div>
<div id="about_layer">
</div>
</body>
</html>

There is nothing wrong with your code , just try running your html file using development server .
You can use Live Server visual studio code extension for that.

Related

How do you add a loading GIF spinner before AOI response in vanilla javascript?

So far I've tried using the let method make the GIF a constant and attempting to switch display type is js style function. Can someone guide me into displaying GIF image before API response and hiding it when fetch() is processed.
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./doggos.css">
<title>Dogs</title>
</head>
<body>
<h1>Doggos</h1>
<button class="add-doggo">Add Doggo</button>
<div class="doggos">
<div class="loader"><img src="./giphy (1).gif"></img></div>
</div>
<script src="./doggos.js"></script>
</body>
</html>
Javascript
const DOG_URL = "https://dog.ceo/api/breeds/image/random";
const doggos = document.querySelector(".doggos");
function addNewDoggo() {
const promise = fetch(DOG_URL);
promise
.then(function(response) {
const processingPromise = response.json(); //This line of code parses the API response into a usuable js object
return processingPromise; //this code returns a new promise and this process is called | PROCESS-CHAINING
})
.then(function(processedResponse) {
const img = document.createElement("img");
img.src = processedResponse.message;
img.alt = "Cute doggo";
doggos.appendChild(img);
});
}
document.querySelector(".add-doggo") .addEventListener("click", addNewDoggo)

Extract text with cheerio

I'm trying to write a script to extract email id and name from this website. I tried the following snippet but it doesn't work.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>foo</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<strong style="color: darkgreen;">Can read this tag</strong>
<object id="external_page" type="text/html" data="https://aleenarais.com/buddy/" width="800px" height="600px"
style="overflow:auto;border:5px ridge blue">
<!-- I want to read tag values from this object -->
</object>
</div>
<script>
window.addEventListener('load', function () {
const item = [];
$('strong[style="color: darkgreen;"]').each(function () {
item.push($(this).text())
})
console.log(item)
})
</script>
</body>
</html>
Is there any better way to do this? Or is it possible to convert the whole page into a string and extract the email using RegEx?
The email and name of in the webpage are being rendered in an iframe. The source of iframe is an external source. In order for you to extract the information, you need to use a headless browser to do that.
I would suggest using Node.JS & Puppeteer (https://www.npmjs.com/package/puppeteer)
const puppeteer = require("puppeteer");
(async() => {
const url = "https://aleenarais.com/buddy/";
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url, {
waitUntil: "networkidle0"
});
var frames = await page.frames();
var myframe = frames.find(
(f) => f.url().indexOf("https://feedium.app/fetchh.php") > -1
);
const textFeed = await myframe.$$eval("strong", (sElements) =>
sElements.map((el) => el.textContent)
);
console.log(textFeed.splice(1)); //Array contains both name and email
await browser.close();
})();
Puppeteer loads the page similar to how a user loads the page. It waits until all the network calls are done (see network idle0) and then it tries finding the iframe which has the url (fetchh.php). If you observe, name and email are present in strong tags and they are the only strong tags available. Hence, we are extracting the strong tags, removing the count and we are left with just the name and email.
Output:
[ 'JJ', 'j*j#gmail.com' ] //I have just masked the values but the program gives the actual ones
Steps to run the script:
Install Node.Js (https://nodejs.org/en/download/)
Install puppeteer using (npm i puppeteer)
copy the script and place it in file (demo.js)
In the terminal, navigate to the directory in which the demo.js is
present and then run node demo.js
You should see the output.
Try this:
window.addEventListener('load', function () {
let item = [];
$('strong[style*="color: darkgreen;"]').each(function (index, item) {
item.push($(this).text())
})
console.log(item)
}

Routing(?) in Vanilla JS

I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");

How to load images in a local zip file in electron webviews?

I can show an image inside a zip file in electron using the following code.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<img src="zip_resources://images.zip/apple.jpg"/>
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</body>
</html>
renderer.js
protocol.registerBufferProtocol("zip_resources", async (request, callback) => {
const urlExploded = request.url.split("/"); // [ 'zip_resources:', '', 'images.zip', 'apple.jpg' ]
const zip = urlExploded[2]; // images.zip
const fileName = urlExploded[3]; // apple.jpg
const fileContents = await extractFileFromZip(zip, fileName);
callback({ data: fileContents, mimeType: "image" });
});
As you can see, to make it work, I created a custom protocol zip_resources:// and told electron how to load resources from this protocol by using registerBufferProtocol. But what if the img tag is in a webview? Like this.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<webview
src="data:text/html,<img src='zip_resources://images.zip/apple.jpg'/>"
/>
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</body>
</html>
How to make webview load this kind of resources correctly?

Firefox not executing scripts loaded dynamically via another external script

I've been having trouble with Firefox not executing JavaScript files that were loaded dynamically via an external script.
Let me explain.
I have the following HTML file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Restive.JS</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="assets/js/load.js"></script>
</head>
<body>
<h1>Loading JavaScript</h1>
</body>
</html>
Inside my load.js file, I have the following code:
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test1.js', 'assets/js/test2.js'];
for (var i = 0; i < list_arr.length; i++) {
loadScript(list_arr[i]);
}
});
And inside test1.js and test2.js, I have console.log('test1.js is loaded!'); and console.log('test2.js is loaded!');.
The problem is that test1.js and test2.js are loaded (I can see both files in the <head> via inspection), but they are never executed (because no messages appear in the console log).
However, when I change the format of script reference in my original HTML by inlining the JavaScript i.e. changing from this:
<script type="text/javascript" src="assets/js/load.js"></script>
to this:
<script>
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test3.js', 'assets/js/test4.js'];
for (var i = 0; i < list_arr.length; i++) {
console.log('i = ' + i);
loadScript(list_arr[i]);
}
});
</script>
Then the scripts are loaded and executed.
I don't see this behaviour in Chrome or Safari, only Firefox. Also, inlining is not an option because this functionality is built-in to a library that users will have to reference via an external link.
Is this a problem that is fixable?
EDIT
I'm on a Mac OSX 10.10.5 using Firefox 46.0.1

Categories