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);
Related
I should loop this json file to javascript, all the entries are important and must be retrieved.
I need to make this json compatible with this javascript code.
This is my json file:
{ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
This is my code javascript:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
var user_token = arr[0].user_token;
for(i = 0; i < arr.length; i++) {
var level = arr[i].level;
out += user_token;
}
document.getElementById("id01").innerHTML = out;
}
var jsonInput={ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
function myFunction(arr) {
var out = "";
var i;
var userLabel=''
var user_token = arr.user_token;
mainArrObj=arr.main_levels
for(i = 0; i < mainArrObj.length; i++) {
var level = mainArrObj[i].level;
out += user_token + ' ';
userLabel += level + ' ';
}
console.log('user_token :'+out);
console.log('userLabel :'+userLabel);
}
myFunction(jsonInput)
I want to get a file from client side to parse it into json object and send it to the backend, i am able to parse the file thanks to Sheet-js.
My problem is i can not get files from client side
I am using js, SAPUI5
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
if (!oFileUploader.getValue().toString()) {
MessageToast.show("Choose a xlsx file first");
return;
}
var url = "/resources/test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = [];
for (var i = 0; i !== data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {
type: "binary"
});
var firstSheetName = workbook.SheetNames[0];
var worksheet = workbook.Sheets[firstSheetName];
var json = XLSX.utils.sheet_to_json(worksheet, {
raw: true
});
var jsonStr = JSON.stringify(json);
MessageBox.show("JSON String: " + jsonStr);
};
oReq.send();
},
The answer is:
UploadFile.view.xml
<VBox>
<u:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}
I have this code, this it's my object:
var sendData = function(ob) {
var obj = ob;
return {
send: function() {
obj.myform.onsubmit = function(e) {
var file = obj.file.files;
var ajax = new XMLHttpRequest();
var formdata = new FormData();
for(var i = 0; i < file.length; i++) {
formdata.append(data[], file[i]);
}
ajax.upload.onprogress = function(event) {
oojs.byID('container').innerHTML = Math.round((event.loaded / event.total)*100)+"%";
}
ajax.onload = function() {
oojs.byID('container').innerHTML = "Done";
}
ajax.onerror = function() {
oojs.byID('container').innerHTML = "Error";
}
ajax.onabort = function() {
oojs.byID('container').innerHTML = "Abort";
}
ajax.open("POST", "result.php");
ajax.send(formdata);
e.preventDefault();
}
}
}
}
oojs.sendData = sendData;
I want for each file one progress bar but, now i have just one progrss bar,
for(var i = 0; i < file.length; i++) {
formdata.append(data[], file[i]);
}
In this loop each file is added to formdata, i want send formdata for each file especially. I'm allready try do like this:
for(var i = 0; i < file.length; i++) {
var formdata = new FormData();
formdata.append(data, file[i]);
// ...
ajax.send(formdata);
}
Could you please try something like this:
function sendFile (file, progressCallback) {
var ajax = new XMLHttpRequest();
var formdata = new FormData();
formdata.append(file.name, file);
ajax.upload.onprogress = function(event) {
progressCallback(Math.round((event.loaded / event.total)*100));
};
ajax.onload = function() {
oojs.byID('container').innerHTML = "Done";
};
ajax.onerror = function() {
oojs.byID('container').innerHTML = "Error";
};
ajax.onabort = function() {
oojs.byID('container').innerHTML = "Abort";
};
ajax.open("POST", "result.php");
ajax.send(formdata);
}
var progress = 0;
var filesLength = files.length;
for(var i = 0; i < filesLength; i++) {
sendFile(files[i], function (x) {
progress = progress + x;
oojs.byID('container').innerHTML = (Math.round((progress / filesLength))) + '%';
});
}
I'm trying to make drag n' drop upload file in JS. I've written code as follow:
<div id="drop_zone">
<div style="clear: both"></div>
</div>
<output id="list"></output>
<script type="text/javascript">
var Vector = function() {
var _array = [];
this.add = function(item) {
_array.push(item);
};
this.delete = function(index) {
_array.splice(index, 1);
};
this.foreach = function(callback) {
for(i=0; i<_array.length; i++) {
callback(_array[i]);
}
};
this.length = function() {
return _array.length;
};
this.clear = function() {
_array = [];
};
};
var Snap = function(args) {
this.name = args.name || null;
this.type = args.type || null;
this.size = args.size || null;
this.modified = args.modified || null;
this.source = args.source || null;
}
var images = new Vector();
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
if(files.length != 0) {
for(var i=0, f; f = files[i]; i++) {
var image = new Snap({
name : escape(f.name),
type : f.type||'n/a',
size : f.size,
modified : f.lastModifiedDate ? f.lastModifiedDate.toLocaleString() : 'n/a'
});
var file = files[i];
var filereader = new FileReader;
filereader.onload = function(e) {
image.source = this.result;
};
filereader.readAsDataURL(file);
images.add(image);
}
}
alert(images.length());
render();
}
function render() {
var list = document.getElementById('list');
images.foreach(function(elem) {
var div = document.createElement('div');
var divtext = elem.name + '(<i>' + elem.type + '</i>), ' + elem.size + ' <small>[' + elem.modified + ']</small>';
div.innerHTML = divtext;
list.appendChild(div);
var img = document.createElement('img');
img.src = elem.source;
document.getElementById('drop_zone').appendChild(img);
});
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy';
}
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
It's not working as I wish.
This view is after I drag image first time. images.length = 1
This view is after I drag image second time. images.length actually = 2, not 3, so Vector images works as it is supposed to work.
View after third dragging, one and the same image. images.length = 3, not 6, so when it comes to Vector, it's ok.
I haven't no idea how to make it works.
Thanks in advance.
got this script that puts urls from a txt file into an i frame and loads them one by one:
<script type="text/javascript">
$.get("imones.txt", function (data) {
var array = data.split(/\r\n|\r|\n/);
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
var beforeTimes = [];
$('#frame_id').on('load', function () {
beforeTimes.push(beforeLoad);
loadTimes.push((new Date()).getTime());
$('#frame_id').attr('src', array.pop());
$.each(loadTimes, function (index, value) {
var result = (value - beforeTimes[index]) / 1000;
if (result < 0) {
result = result * (-1);
}
$("#loadingtime" + index).html(result);
beforeLoad = value;
});
}).attr('src', array.pop());
});
</script>
My problem - it put urls not by order, i want it to start from the bottom or top and then ony by one put them in order. How do i do that?
Try this
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "imones.txt", true);
txtFile.onreadystatechange = function()
{
if (txtFile.readyState === 4) // Makes sure the document is ready to parse.
{
if (txtFile.status === 200) // Makes sure it's found the file.
{
allText = txtFile.responseText;
}
}
}