How to open array of links correctly? - javascript

I have a question, how do I open all link from an array at the same time, not only one like it does now, I've tried something like this:
var urls = ["https://www.google.com", "https://www.facebook.com"];
let main = function() {
for (var i = 0; i < urls.length; i++) {
window.open(urls[i], '_blank');
}
};
main();
Can anybody show some examples? Thanks! :p

<html>
<head>
<script type='text/javascript'>
var urls = ["https://www.google.com", "https://www.facebook.com"];
function main() {
for (var i = 0; i < urls.length; i++) {
var el = document.querySelector('#hidden') ;
//window.open(urls[i], '_blank');
var a = document.createElement('a');
a.href = urls[i];
a.target = '_blank';
el.appendChild(a);
a.click();
}
}
window.addEventListener('load', function () { main();}, !1);
</script>
</head>
<body>
<div id='hidden'></div>
</body>
</html>

Related

.send(formData) Error "GET 404 .../upload.php (Not Found)"

i've found this code on a website for uploading files using javascript, but it doesn't seems to work. Could somebody help me with that please?
Index.php :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div class="row">
<div id="uploads"></div>
<div class="dropzone" id="dropzone">
Drop files fere to upload
</div>
</div>
</div>
<script src="js_script.js" type="text/javascript"></script>
</body>
</html>
And js :
(function() {
var dropzone = document.getElementById('dropzone');
var displayUploads = function(data) {
var uploads = document.getElementById('uploads'),
anchor,
x;
for (x = 0; x < data.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = data[x].file;
anchor.innerText = data[x].name;
uploads.appendChild(anchor);
}
};
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for (x = 0; x < files.length; x = x + 1) {
formData.append('file[]', files[x]);
}
xhr.onload = function() {
var data = JSON.parse(this.responseText);
displayUploads(data);
};
xhr.open('post', 'upload.php');
xhr.send(formData);
};
dropzone.ondrop = function(e) {
e.preventDefault();
this.className = 'dropzone';
upload(e.dataTransfer.files);
};
dropzone.ondragover = function() {
this.className = 'dropzone dragover';
return false;
};
dropzone.ondragleave = function() {
this.className = 'dropzone';
return false;
};
}());
and upload.php :
<?php
header("Content-Type: application/json");
$uploaded = array();
if(!empty($_FILES['file']['name'][0])){
foreach($_FILES['file']['name'] as $position => $name){
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], 'uploads/'.$name)){
$uploaded[] = array(
'name' => $name,
'file' => 'uploads/'.$name
);
}
}
}
echo json_encode($uploaded);
?>
And now this issue :
GET .../upload.php 404 (Not Found)
and related code to issue :
xhr.send(formData);
btw what is that "GET" showing in console??
I just saved the file "Upload.php" with uppercase "U" which should be "upload.php".

How to get not loaded resources?

I'm trying to get all not loaded elements in a webpage by including a script in the head of the index.html but I've some problems.
This is the code:
document.addEventListener('DOMContentLoaded', function () {
console.log("here");
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
scripts[i].onerror =function(message, source, lineno) {
console.log("JS: Error SCRIPT");
}
}
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
imgs[i].onerror =function(message, source, lineno) {
console.log("JS: Error IMG ");
}
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
links[i].onerror = function(message, source, lineno){
console.log("JS: Error CSS ");
}
}
});
I put 3 wrong CSS, Images and Scripts (they don't exist as resources) inside the HTML file where I call the script.
When I run locally the index.html I get "Error IMG" and "Error CSS".
When I run on the server I get only "Error IMG".
In both cases, I don't get "Error SCRIPT".
What I'm doing wrong?
UPDATE: This is the code
appmetrics.js
//class that store page resource data
/*
ES6
class Resource{
constructor(name,type,start,end,duration){
this.name = name;
this.type = type;
this.start = start;
this.end = end;
this.duration = duration;
}
}
*/
function Resource (name,type,start,end,duration){
this.name = name;
this.type = type;
this.start = start;
this.end = end;
this.duration = duration;
}
/*
ES6
class Errors{
constructor(name,source,line){
this.name = name;
this.source = source;
this.line = line;
}
}
*/
function Errors(name,source,line){
this.name = name;
this.source = source;
this.line = line;
}
//endpoint to send data
var endpoint = "https://requestb.in/sr8wnnsr"
var resources = Array();
var errors = Array();
var pageLoadTime;
var start = performance.now();
window.onload = function(){
pageLoadTime = performance.now()-start;
console.log("Page loading time: " + pageLoadTime);
//getting page resources and pushing them into the array
var res = performance.getEntriesByType("resource");
res.forEach(function add(item){
resources.push(new Resource(item.name,item.initiatorType,item.startTime,item.responseEnd,item.duration));
})
console.log(resources);
var jsonRes = JSON.stringify(resources);
//sendMetricToEndpoint(jsonRes);
//sendMetricToEndpoint(pageLoadTime.toString());
}
window.onerror = function(message, source, lineno) {
console.log("Error detected!" + "\nMessage: " +message +"\nSource: "+ source +"\nLine: "+ lineno);
errors.push(new Errors(message,source,lineno));
console.log(errors);
}
//Not working code
/*
document.addEventListener('DOMContentLoaded', function () {
console.log("here");
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
scripts[i].onerror =function(message, source, lineno) {
console.log("JS: Errore SCRIPT");
}
}
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
imgs[i].onerror =function(message, source, lineno) {
console.log("JS: Errore IMG ");
}
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
links[i].onerror = function(message, source, lineno){
console.log("JS: Errore CSS ");
}
}
});
*/
//StackOverflow solution start
var scripts = [];
for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) {
scripts[i] = { source: nodes[i].src, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = scripts.findIndex(function(script) {
return script.source === loadedNode.src;
});
scripts[index].loaded = true;
};
}
var links = [];
for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) {
links[i] = { source: nodes[i].href, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = links.findIndex(function(link) {
link.href === loadedNode.href;
});
links[index].loaded = true;
};
}
document.addEventListener('DOMContentLoaded', function() {
console.log("here");
scripts.filter(function(script) {
return !script.loaded;
}).forEach(function(script) {
console.log("Error loading script: " + script.source);
});
links.filter(function(link) {
return !link.loaded;
}).forEach(function(link) {
console.log("Error loading link: " + link.source);
});
// and the rest of the elements
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onerror = function() {
console.log("Error loading image: " + this.src);
};
}
});
//StackOverflow solution stop
/**
* Function that send metric to endpoint.
*
* #param {string} endpoint Where to send data.
* #param {*} data data to send (JSON or string)
*/
function sendMetricToEndpoint(data){
console.log("Sending metrics to endpoint");
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
};
xhttp.open("POST", endpoint, true);
//xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(data);
}
index.html
<html>
<head>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>-->
<script src="js/appmetricsmod.js"></script>
<link rel="stylesheet" href="styletests.css">
<link rel="stylesheet" href="styletestss.css">
<link rel="stylesheet" href="styletestsss.css">
<script src="js/error1.js"></script>
<script src="js/error2.js"></script>
<script src="js/error3.js"></script>
</head>
<body>
<img src="imgtest.png"></img>
<img src="imgErr1.png"></img>
<img src="imgErr2.png"></img>
<img src="imgErr3.png"></img>
<img src="http://images.centrometeoitaliano.it/wp-content/uploads/2016/11/15/l1.jpg"></img>
<div class="divtest">
hello this is a test
</div>
<script>
</script>
</body>
</html>
Sadly, you you cannot get link nor script error load with onerror event, but you can handle the loaded content, and filter which were not loaded. This is possible with the load event for the link and script tags.
var scripts = [];
for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) {
scripts[i] = { source: nodes[i].src, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = scripts.findIndex(function(script) {
return script.source === loadedNode.src;
});
scripts[index].loaded = true;
};
}
var links = [];
for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) {
links[i] = { source: nodes[i].href, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = links.findIndex(function(link) {
link.href === loadedNode.href;
});
links[index].loaded = true;
};
}
document.addEventListener('DOMContentLoaded', function() {
console.log("here");
scripts.filter(function(script) {
return !script.loaded;
}).forEach(function(script) {
console.log("Error loading script: " + script.source);
});
links.filter(function(link) {
return !link.loaded;
}).forEach(function(link) {
console.log("Error loading link: " + link.source);
});
// and the rest of the elements
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onerror = function() {
console.log("Error loading image: " + this.src);
};
}
});
Hope it helps :)
Using the classes Resources and Errors above, I solved the problem by taking all the resources of the page and then removing the working ones. The result is an array of not loaded resources.
This is the code:
var res = performance.getEntriesByType("resource");
res.forEach(function add(item){
resources.push(new Resource(item.name,
item.initiatorType,
item.startTime,
item.responseEnd,
item.duration));
})
var flag = true;
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
for(var j=0;j<resources.length;j++){
if(imgs[i].src == resources[j].name){
flag = false;
}
}
if(flag && imgs[i].src){
errors.push(new Errors("RES NOT FOUND",imgs[i].src,null));
}
flag = true;
}
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
for(var j=0;j<resources.length;j++){
if(scripts[i].src == resources[j].name){
flag = false;
}
}
if(flag && scripts[i].src){
errors.push(new Errors("RES NOT FOUND",scripts[i].src,null));
}
flag = true;
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
for(var j=0;j<resources.length;j++){
if(links[i].src == resources[j].name){
flag = false;
}
}
if(flag && links[i].href){
errors.push(new Errors("RES NOT FOUND",links[i].href,null));
}
flag = true;
}
console.log(resources);
console.log(errors);

How to create a screenshot of browser window and save it to another page

I would like to ask what is the logic behind capturing the screen of browser window.Can we open this screenshot image in popup where user have an option to save the screenshot.
Here is my code In this code the Problem is that my browser screen have image also it captures text but not capturing image I couldn't get where the problem is ? Here is my code
<html lang="en">
<head>
<title>Take Web Page Screenshot with HTML5 and JavaScript </title>
</head>
<body>
<div>
<div style="background-image:url('assets/images/act.png');height: 50px;width: 50px;"></div>
<div><a class="btn btn-success" href="javascript:void(0);" onclick="generate()">Generate
Screenshot ยป</a>
</div>
<div>fsaffsfasfasfasfasfasff</div>
</div>
<script type="text/javascript">
(function (exports) {
function urlsToAbsolute(nodeList) {
console.log(nodeList);
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__===HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function (el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
console.log(absURL);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
urlsToAbsolute(document.images);
urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
var screenshot = document.documentElement.cloneNode(true);
var b = document.createElement('base');
b.href = document.location.protocol + '//' + location.host;
var head = screenshot.querySelector('head');
head.insertBefore(b, head.firstChild);
screenshot.style.pointerEvents = 'none';
screenshot.style.overflow = 'hidden';
screenshot.style.webkitUserSelect = 'none';
screenshot.style.mozUserSelect = 'none';
screenshot.style.msUserSelect = 'none';
screenshot.style.oUserSelect = 'none';
screenshot.style.userSelect = 'none';
screenshot.dataset.scrollX = window.scrollX;
screenshot.dataset.scrollY = window.scrollY;
var script = document.createElement('script');
script.textContent = '(' + addOnPageLoad_.toString() + ')();';
screenshot.querySelector('body').appendChild(script);
var blob = new Blob([screenshot.outerHTML], {
type: 'text/html'
});
return blob;
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function (e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
window.URL = window.URL || window.webkitURL;
window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
</script>
</body>
</html>

How to read simultaneously two text files using HTML5 and Javascript

I'm using HTML5 and JavaScript for reading a text file, but now I need to read exactly 2 text files and do the same operations as done before but for the two files.
For the second file I've been trying with: var file2 = files[1]; and add a multiplein the html input, but how can I do it for the reader.onload = function (e) { part? I want to parse the two files in the same way, not only one.
Here is the code (simplified):
<!DOCTYPE html>
<html>
<head>
<title>Read and Parse Lynis Log</title>
<script>
function processFiles(files) {
var file = files[0];
var reader = new FileReader();
var textParsed = [];
reader.onload = function (e) {
var output = document.getElementById("fileOutput");
output.textContent = e.target.result;
var text = e.target.result;
var lines = text.split("\n");
for (var i= 0; i < lines.length; i++) {
textParsed[i] = lines[i];
}
var testsPerformed = null;
var suggestions = [];
var suggestion = null;
var auxSug = null;
for (var j = 0; j < lines.length; j++) {
if (textParsed[j].includes("tests_executed")){
testsPerformed = textParsed[j];
}
if (textParsed[j].includes("suggestion[]")) {
suggestion = textParsed[j];
suggestions.push(suggestion);
}
}
if (typeof(Storage) !== "undefined" && textParsed.length >= 1) {
//Store
localStorage.setItem('storedText', textParsed);
localStorage.setItem('tests', testsPerformed);
localStorage.setItem('suggestions', suggestions);
}
};
reader.readAsText(file);
}
</script>
</head>
<body>
<input id="fileInput" placeholder=":input" type="file" size="50" onchange="processFiles(this.files)">
<div id="fileOutput"></div>
</body>
</html>
You only need to initialize a FileReader for each file and start readAsText for every file. The function will be the same, I've modify the output so the content is not cleared with each file that is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Read and Parse Lynis Log</title>
<script>
function processFiles(files) {
var file = files[0];
var textParsed = [];
function onReadAsText(e) {
var output = document.getElementById("fileOutput");
output.textContent = output.textContent + e.target.result;
var text = e.target.result;
var lines = text.split("\n");
for (var i= 0; i < lines.length; i++) {
textParsed[i] = lines[i];
}
var testsPerformed = null;
var suggestions = [];
var suggestion = null;
var auxSug = null;
for (var j = 0; j < lines.length; j++) {
if (textParsed[j].includes("tests_executed")){
testsPerformed = textParsed[j];
}
if (textParsed[j].includes("suggestion[]")) {
suggestion = textParsed[j];
suggestions.push(suggestion);
}
}
if (typeof(Storage) !== "undefined" && textParsed.length >= 1) {
//Store
localStorage.setItem('storedText', textParsed);
localStorage.setItem('tests', testsPerformed);
localStorage.setItem('suggestions', suggestions);
}
};
for (var i = 0; i < files.length; i++){
var reader = new FileReader();
reader.onload = onReadAsText;
reader.readAsText(files[i]);
}
}
</script>
</head>
<body>
<input id="fileInput" placeholder=":input" type="file" size="50" onchange="processFiles(this.files)" multiple>
<div id="fileOutput"></div>
</body>
</html>

Meteor: large base64 files preventing download

I am trying to download files that were uploaded from MongoDB using gridfs. The download works for small files but does not work for files bigger than 1MB, no error message no thing happens. Is there a way around the file size issue?
Event:
Template.form.events({
"click #chunk": function() {
let doc = Images.findOne({_id:"TK8mmSg9CvjxwSxE5"});
let chunk = filenamechunks.find({files_id:new Meteor.Collection.ObjectID(doc.copies.images.key)}).fetch();
if (chunk.length > 0) {
let chunksize = 0xffff;
let len = chunk[0].data.length;
let strings = [];
for (var y = 0; y < chunk.length; y++) {
for (var i = 0; i * chunksize < len; i++){
strings.push(String.fromCharCode.apply(null, chunk[y].data.subarray(i * chunksize, (i + 1) * chunksize)));
};
};
let content = btoa(strings.join(''));
let link = window.document.createElement("a");
link.setAttribute("href", "data:"+doc.copies.type+";base64," + content);
link.setAttribute("download", "test."+doc.copies.name.split(".")[1]);
link.click();
};
}
});
HTML:
<template name="form">
<button id="chunk">click</button>
</template>
Publish:
Meteor.publish("chunks", function(id){
return filenamechunks.find({files_id:new Meteor.Collection.ObjectID(id)});
});
Subscribe:
Template.form.onCreated(function() {
this.subscribe("chunks","56fbaa2c850d6b341a0c3344");
});
Packages:

Categories