I am new to JavaScript and I have an html page that loads the source code from this page into a given div and I am using the code provided by the user rob-w which works fine but my main goal is to learn how to show only part of the returned text starting at a given value and ending at a given value after that
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector("#message");
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
window.onload = onWindowLoad;
getPagesSource.js
// #author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
I have played around with many DOM functions and getBy functions but I have not been able to apply them correctly and I don't think they are exactly what I am after. If someone can point me in the right direction it would be appreciated
My solution uses String.prototype.match() to get an array containing all values between strings x and y but not including strings x and y.
function getStringsBetweenXandY(html) {
var matches = html.match(/x[\s\S]*?y/g), i = matches.length;
while(i--) {
matches[i] = matches[i].match(/x([\s\S]*?)y/)[1];
}
return matches;
}
var array = getStringsBetweenXandY(html);
You need to make sure that strings x and y contain backslashes where necessary.
matches will contain an array or an array-like object containing all of the html fragments you are looking for
I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?
While invoking a http adapter procedure, it popsup a dialog with ProcedureName, Signature and Paramaters and when I hit Run button after entering two string type parameters, I am getting "Class Cast: java.lang.String cannot be cast to org.mozilla.javascript.Scriptable" error.
FYI, I created a worklight adapter using worklight application framework data object editor(automatically generates .xml and impl.js files)
impl.js file
function CurrencyConvertor_ConversionRate(params, headers){
var soapEnvNS;
soapEnvNS = 'http://schemas.xmlsoap.org/soap/envelope/';
var request = buildBody(params, 'xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://www.webserviceX.NET/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" ', soapEnvNS);
return invokeWebService(request, headers);
}
function buildBody(params, namespaces, soapEnvNS){
var body =
'<soap:Envelope xmlns:soap="' + soapEnvNS + '">\n' +
'<soap:Body>\n';
body = jsonToXml(params, body, namespaces);
body +=
'</soap:Body>\n' +
'</soap:Envelope>\n';
return body;
}
function getAttributes(jsonObj) {
var attrStr = '';
for(var attr in jsonObj) {
var val = jsonObj[attr];
if (attr.charAt(0) == '#') {
attrStr += ' ' + attr.substring(1);
attrStr += '="' + val + '"';
}
}
return attrStr;
}
function jsonToXml(jsonObj, xmlStr, namespaces) {
var toAppend = '';
for(var attr in jsonObj) {
var val = jsonObj[attr];
if (attr.charAt(0) != '#') {
toAppend += "<" + attr;
if (typeof val === 'object') {
toAppend += getAttributes(val);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val, toAppend);
}
else {
toAppend += ">" + val;
}
toAppend += "</" + attr + ">\n";
}
}
return xmlStr += toAppend;
}
function invokeWebService(body, headers){
var input = {
method : 'post',
returnedContentType : 'xml',
path : '/CurrencyConvertor.asmx',
body: {
content : body.toString(),
contentType : 'text/xml; charset=utf-8'
}
};
//Adding custom HTTP headers if they were provided as parameter to the procedure call
headers && (input['headers'] = headers);
return WL.Server.invokeHttp(input);
}
The error indicates that there is an invalid JSON object somewhere in your code.
Most probably this error raised while converting the body to String using body.toString()
as toString will return [object Object] which is invalid JSON object value (neither valid String nor valid Array)
use json.stringify(body) instead, it should make what you intended to do.
besides, try to add some log lines to ease tracing the error
I am trying to export a file as .csv file so that when the user clicks on the download button, the browser would automatically download the file as .csv.
I also want to be able to set a name for the .csv file to be exported
I am using javascript to do this
The code is below:
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
// Example
$(document).ready(function () {
// Create Object
var items = [
{ "name": "Item 1", "color": "Green", "size": "X-Large" },
{ "name": "Item 2", "color": "Green", "size": "X-Large" },
{ "name": "Item 3", "color": "Green", "size": "X-Large" }];
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
$("#download").click(function() {
alert("2");
var csv = ConvertToCSV(jsonObject);
window.open("data:text/csv;charset=utf-8," + escape(csv))
///////
});
});
I have written a solution in this thread: How to set a file name using window.open
This is the simple solution:
$("#download_1").click(function() {
var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
var json = $.parseJSON(json_pre);
var csv = JSON2CSV(json);
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "data.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
JSON2CSV function:
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
if ($("#labels").is(':checked')) {
var head = array[0];
if ($("#quote").is(':checked')) {
for (var index in array[0]) {
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[0]) {
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for (var i = 0; i < array.length; i++) {
var line = '';
if ($("#quote").is(':checked')) {
for (var index in array[i]) {
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
} else {
for (var index in array[i]) {
line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return str;
}
in modern browsers there is a new attribute in anchors.
download
http://caniuse.com/download
so instead of using
window.open("data:text/csv;charset=utf-8," + escape(csv))
create a download link:
download
another solution is to use php
EDIT
i don't use jQuery, but you need to edit your code to add the download link
with something like that in your function.
var csv=ConvertToCSV(jsonObject),
a=document.createElement('a');
a.textContent='download';
a.download="myFileName.csv";
a.href='data:text/csv;charset=utf-8,'+escape(csv);
document.body.appendChild(a);
Try these Examples:
Example 1:
JsonArray = [{
"AccountNumber": "1234",
"AccountName": "abc",
"port": "All",
"source": "sg-a78c04f8"
}, {
"Account Number": "1234",
"Account Name": "abc",
"port": 22,
"source": "0.0.0.0/0",
}]
JsonFields = ["Account Number","Account Name","port","source"]
function JsonToCSV(){
var csvStr = JsonFields.join(",") + "\n";
JsonArray.forEach(element => {
AccountNumber = element.AccountNumber;
AccountName = element.AccountName;
port = element.port
source = element.source
csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n";
})
return csvStr;
}
You can download the csv file using the following code :
function downloadCSV(csvStr) {
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr);
hiddenElement.target = '_blank';
hiddenElement.download = 'output.csv';
hiddenElement.click();
}
I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.
I use $.getJSON to pull json data from an external page, but if you have a basic array, you can just use that.
This uses Christian Landgren's code to create the csv data.
$(document).ready(function() {
var JSONData = $.getJSON("GetJsonData.php", function(data) {
var items = data;
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(items[0]);
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
csv = csv.join('\r\n');
//Download the file as CSV
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "DataDump.csv"; //Name the file here
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
});
Edit: It's worth noting that JSON.stringify will escape quotes in quotes by adding \". If you view the CSV in excel, it doesn't like that as an escape character.
You can add .replace(/\\"/g, '""') to the end of JSON.stringify(row[fieldName], replacer) to display this properly in excel (this will replace \" with "" which is what excel prefers).
Full Line: JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""')
One-liner function for simple JSON with static titles
Assuming arr is JSON array, you can also replace the first string with comma separated titles end with \n
arr.reduce((acc, curr) => (`${acc}${Object.values(curr).join(",")}\n`), "")
Or with the window.open function mentioned before
window.open(`data:text/csv;charset=utf-8,${arr.reduce((acc, curr) => (`${acc}${Object.values(curr).join(",")}\n`), "")}`)
You should also consider escape the strings or replace the , to avoid extra cells
If your data comes from a SQL Database, all your lines should have the same structure, but if coming from a NoSQL Database you could have trouble using standard answers. I elaborated on above JSON2CSV for such a scenario.
Json data example
[ {"meal":2387,"food":"beaf"},
{"meal":2387,"food":"apple","peeled":"yes", "speed":"fast" },
{"meal":2387,"food":"pear", "speed":"slow", "peeled":"yes" } ]
Answer
"meal","food","peeled","speed"
"2387","beaf","",""
"2387","apple","yes","fast"
"2387","pear","yes","slow"
Code for headers and double quotes for simplicity.
function JSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
// get all distinct keys
let titles = [];
for (var i = 0; i < array.length; i++) {
let obj = array[i];
Object.entries(obj).forEach(([key,value])=>{
//console.log('key=', key, " val=", value );
if (titles.includes(key) ) {
// console.log (key , 'exists');
null;
}
else {
titles.push(key);
}
})
}
let htext = '"' + titles.join('","') + '"';
console.log('header:', htext);
// add to str
str += htext + '\r\n';
//
// lines
for (var i = 0; i < array.length; i++) {
var line = '';
// get values by header order
for (var j = 0; j < titles.length; j++) {
// match keys with current header
let obj = array[i];
let keyfound = 0;
// each key/value pair
Object.entries(obj).forEach(([key,value])=>{
if (key == titles[j]) {
// console.log('equal tit=', titles[j] , ' e key ', key ); // matched key with header
line += ',"' + value + '"';
keyfound = 1;
return false;
}
})
if (keyfound == 0) {
line += ',"' + '"'; // add null value for this key
} // end loop of header values
}
str += line.slice(1) + '\r\n';
}
return str;
}
I want to convert a JSON object to a XML String and I can't figure a proper way to do it.
I've found a neat little jQuery plugin called json2xml at https://gist.github.com/c4milo/3738875 but it doesn't escape the data.
How can I escape the data properly so that the browser's XML parser will work?
You can try this small library http://code.google.com/p/x2js/
There is no unique way of doing this. You should be using XML with a schema only, and JSON doesn't have such a schema. Any such transformation when done naively is likely to break.
Why don't you just use XML or JSON consequently?
You can use the external js available by google named x2js.js
You can see the demo over here.
jsFiddle Demo
you can use this function in your code to convert JSON to XML in js
var json2xml = function (o) {
var tab = "\t";
var toXml = function (v, name, ind) {
var xml = "";
if (v instanceof Array) {
for (var i = 0, n = v.length; i < n; i++)
xml += ind + toXml(v[i], name, ind + "\t") + "\n";
}
else if (typeof (v) == "object") {
var hasChild = false;
xml += ind + "<" + name;
for (var m in v) {
if (m.charAt(0) == "#")
xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
else
hasChild = true;
}
xml += hasChild ? ">" : "/>";
if (hasChild) {
for (var m in v) {
if (m == "#text")
xml += v[m];
else if (m == "#cdata")
xml += "<![CDATA[" + v[m] + "]]>";
else if (m.charAt(0) != "#")
xml += toXml(v[m], m, ind + "\t");
}
xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
}
}
else {
xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
}
}
return xml;
};
you get XML DOM in return, which in return you need to serialize
so in the main
var xmlDOM = json2xml(eval(jsonObj));
var oSerializer = new XMLSerializer();
var sXML = oSerializer.serializeToString(xmlDOM);