Get data from script code - javascript

I want to get data from a website, can I get url data from code?
Example code:
<script type="application/json" id="store">
{
"url":{"host":"localhost"},
"resources":
{
"xxfff":
{
"stream":
{
"streamId":"","duration":212714,"videos":
[
{
"url":"www.test.com"
},
{
"url":"www.site.net"
}
]
}
}
},
}
</script>
I just want to get "www.site.net" from script code, is it possible?

This is absolutely possible. To demonstrate, I'm going to show you how you could create such an element in the first place, and then how to retrieve the data. If you are manually putting the code in the script tag, I would suggest stringifying it first.
let src = document.createElement('script');
src.setAttribute('id', 'store');
let json = {
url : {
host : "localhost"
},
resources : {
xxfff : {
stream : {
streamId : "",
duration : 212714,
videos : [
{
url : "www.test.com"
},
{
url : "www.site.net"
}
]
}
}
}
};
json = JSON.stringify(json);
src.innerText = json;
const body = document.getElementsByTagName('body')[0];
const footer = document.getElementById('footer');
body.insertBefore(src, footer);
// Now you have created the element,
// so you reverse the process to get your data
src = document.getElementById('store');
json = src.innerText;
json = JSON.parse(json);
let sites = json.resources.xxfff.stream.videos;
sites.map(site => console.log(site.url));

If you mean you have this script tag somewhere in your webpage, you can read it as any other tag, using innerHTML (right in the first line of this snippet):
var json=document.getElementById("store").innerHTML;
var data=JSON.parse(json);
var videos=data.resources.xxfff.stream.videos;
var table=document.getElementById("tbl");
videos.forEach(function(urlObj){
var td=document.createElement("td");
td.innerHTML=urlObj.url;
var tr=document.createElement("tr");
tr.appendChild(td);
table.appendChild(tr);
});
<script type="application/json" id="store">
{
"url":{"host":"localhost"},
"resources":
{
"xxfff":
{
"stream":
{
"streamId":"","duration":212714,"videos":
[
{
"url":"www.test.com"
},
{
"url":"www.site.net"
}
]
}
}
}
}
</script>
<table border="1" id="tbl"></table>
On a side note, there was a surplus comma in your original post (right before the last closing curly brace) which made the entire thing invalid. I removed it in the hopes of it was just some copy-paste issue, perhaps you had more fields just wanted to cut the post shorter.
Also, if you generate this data immediately into the page, you could just let it be "normal" script, and surround it with a simple var data= and ; pair. Then it would be a variable already, without the need for parsing.

Related

Print linked to the logical value

Good morning I wanted help for a code that can use a logical value example:
`` `
function provaIf2(){
var A2=SpreadsheetApp.getActive().getRange('A2').getValue();
var C4=SpreadsheetApp.getActive().getRange('C4').getValue();
if(A2=="") SpreadsheetApp.getActive().getRange('B2').activate();
else if(A2<C4) Print the sheet
else if(A2==C4) Print the sheet
else SpreadsheetApp.getActive().getRange('B3').activate();
}
If you want to print a document using Apps Script, you will have to use Google Cloud Print.
As explained in this article here, you will have to create an Apps Script project in which you include the OAuth2 library. Then you need to get the Google Cloud Print service, send the request and last but not least, print the document.
The below code snippet is used to print the document with the desired options:
function printGoogleDocument(docID, printerID, docName) {
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR",
vendor_id: "Color"
},
duplex: {
type: "NO_DUPLEX"
}
}
};
var payload = {
"printerid" : printerID,
"title" : docName,
"content" : DriveApp.getFileById(docID).getBlob(),
"contentType": "application/pdf",
"ticket" : JSON.stringify(ticket)
};
Reference: Automatically Print Files Placed in Drive with Google Cloud Print and Apps Script.

Only eval a specific js function in a string

I'm using this override to get the content of a js file as a string.
Content of the variable where the js file is loaded into:
<html>
<body>
//META{"name":"testPlugin"}*//
function testPlugin() {
var settings = {
testSettingBool : true,
testSettingInt : 123,
testSettingStr : "Test String",
}
}
testPlugin.prototype.getName = function() { return "Test"; };
testPlugin.prototype.getDescription = function() { return "Test Description"; };
testPlugin.prototype.getVersion = function() { return "1.0"; };
</body>
</html>
Now i only want to eval a special function in that string like
testPlugin.prototype.getVersion();
Thanks for any help :)

JSON file (Extracting data)

I have the following data in a JSON file (pio2.json)
{
"controles":[{
"chart":[{
"type":"columns",
"title":"Pollitos"
}],
"datos":[{"key":"Math","value":98},
{"key":"Physics","value":78},
{"key":"Biology","value":70},
{"key":"Chemistry","value":90},
{"key":"Literature","value":79}
]
}]
}
I need to extract data in array for a chart from "datos" for my html / javascript
$(function () {
var processed_json = new Array();
$.getJSON('pio2.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
}
}
Any advice?
not sure what your issue is. I should be serialized server side and deserialized client side. When deserialized, it will be in an array.
I copied your data, as is, into json1.json pasted in your code and made some minor changes and it worked fine. I got the results out of the json page into my html page.
<body>
<script type="text/javascript">
$(document).ready(function () {
var processed_json = new Array();
$.getJSON('json1.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
})
});
</script>
</body>

Display JSON dictionary in browser using html

So I've looked and looked and looked at different answers on StackExchange and other web forums and I still don't understand this.
I've got a .json file that contains the information from an excel document.
I want to display it on a web browser -> the easiest way to do this seems to be writing it in html.
How do I open the JSON file with html?? I'm happy with having the entire JSON file displayed on the html script but I would love to be able to set is as a variable and pull things out of it like a normal JSON object.
I have the code below for making a table which is what I want to do - but the real JSON object is in a separate file.
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }
],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }
]
}
var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i=0;i<books.Scala.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
To clarify: The above code works great; but I want to do it with the contents of a .json file saved on my local drive.
Thanks in advance.
I see that you didn't include the jquery tag, so I'll provide a couple of vanilla javascript solutions:
If the file is located at an accesible directory, you can pull the data like this:
Define your JSON object as follows:
Original:
[{ "name" : "John", "date" : "01-27-2014" }]
Modified into javascript:
var data = '[{ "name" : "John", "date" : "01-27-2014" }]';
And save it to a plain text document named mydata.json.js, for example (the double extension has nothing to do with the content itself).
So it becomes a valid javascript file and you can load it on your html like this:
<script src="mydata.json.js"></script>
And you can use your data var on your HTML normally.
Or use this if you don't have the document locally or the above approach is too makeshifty for you. Refer to this question. Quoting:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (success) {
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
Update:
You can create a global var, e.g. data, to store the retrieved JSON and redefine the function as follows:
if (xhr.readyState === 4 && xhr.status === 200) {
data = JSON.parse(xhr.responseText); // This now contains the JSON object.
}
Note that xhr.responseText is the raw JSON string and the JSON.parse(…) functions returns a javascript collection with the data of that JSON.
You need to pull JSON using AJAX.
This will require you to have web server running, as some browsers, e.g. Chrome will block requests to local resources. Also have in mind that AJAX & JSON request will work only within the same domain (same origin policy), or you will have to use JSONP.
If you can use jQuery (hence it's an easiest way), look here: http://api.jquery.com/jquery.getjson/
$.getJSON( "test.json", function( data ) {
$.each( data, function( key, val ) {
// do something
});
});
Hope it helps!
You can do this without the need for ajax by using a server side language such as PHP. You can include the raw JSON into a Javascript variable.
Below is an example of including the file with PHP:
<script>
//JSON included via PHP
var books = <?php include('books.json'); ?>;
</script>
The file "books.json" would contain your raw JSON information:
{ "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }
],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }
]
}

document.write in Chrome Extension

I'm new to this so please bear with me. I am trying to write a chrome extension that does the following:
Detect www.website.com/anypage.html. If this website is detected, then do the following.
Don't load the URL.
Instead, write a blank document with a hyperlink to www.website.com/anypage.html?ie=UTF8
The script is set to run at document start (in the manifest).
Here is my code:
Detect URL:
var regExp = /website.com/gi;
var match = 0;
testString = window.location.href.toString();
if(regExp.test(testString) {
match = 1;
Write blank document with link to the URL with the UTF8 encoding tag:
document.write("<a href=" + window.location.href + "?ie=UTF8>Title of Link</a>");
This doesn't work as expected, and just shows a blank page. Anyone have any ideas?
Thanks!
EDIT: Here is the full code:
checklink(); // If there is a match, then checklink will return a 1. If it's already tagged, it will return a 5.
var matchLink = null;
if (checklink() === 1) {
matchLink = window.location.href.toString();
if (checklink() != 1) {
matchLink = null;
function checklink() { //checks to see if the current URL matches website.com
var regExp = /website.com/gi,
testString = window.location.href.toString(),
match = 0,
tagged = 0;
if (regExp.test(testString)) { //if there is a match, returns 1
match = 1;
var regExp2 = /UTF8/gi;
if (regExp2.test(testString)) { //if UTF8 is found, then it returns 5
tagged = 5;
return(match + tagged);
function tagUTF() {
if (matchLink) {
var newLink = matchLink + "?ie=UTF8";
document.write("Link");
if (matchLink) {
tagUTF();
}
The chrome content script has access to the DOM, so you could just replace the contents of the body element of the current page with a new node that has your anchor tag either using dom manipulation methods or innerHTML:
document.body.innerHTML = "<a href=" + window.location.href + "?ie=UTF8>Title of Link</a>";
Please note, this assumes that the JavaScript that is doing the DOM manipulation was properly added for your Chrome extension as a "content script":
http://code.google.com/chrome/extensions/content_scripts.html
EDIT:
Here is the code I used to make it work for me locally:
manifest.json
{
"name": "Test",
"version": "1.0",
"description": "Test",
"permissions": [
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-script.js"],
"run_at": "document_end"
}
]
}
content-script.js
document.body.innerHTML = "<a href='test'>test</a>";

Categories

Resources