Access Json-Object that is not stored inside a variable [duplicate] - javascript

I am trying to access the content in eventbrite emails that I receive but the html code doesn't have an ID associated to the JSON-LD script. So is there a way to still access this data? If so, how?
Is it possible to perhaps attach a temporary id to the JSON-LD script tag so that I can access the data? If so, how?

You can get all JSON-LD blocks with
document.querySelectorAll('script[type="application/ld+json"]');
or just the first one with
document.querySelector('script[type="application/ld+json"]');
Here's a full example:
var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
document.getElementById('result').innerText = jsonld.endDate;
<html>
<head>
<script type="application/ld+json">
{
"#context": "http://schema.org",
"#type": "Event",
"name": "A random event",
"startDate": "2013-09-14T21:30",
"endDate": "2013-09-14T21:30"
}
</script>
</head>
<body>
<p>The end date is: <strong id="result"></strong></p>
</body>
</html>

function myFunction() {
var todayDate = new Date();
var label = GmailApp.getUserLabelByName("eventbrite");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
threads[i].getMessages()[i].getBody().forEach(
var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
document.getElementById('result').innerText = jsonld.endDate;
if (jsonld.endDate > todayDate){
threads[i].markUnread();
}
)
}
}

Related

JavaScript not changing DOM in my HTML Template after load in Apps Script

I am trying to build a simple dashboard where if user access their dashboard it will show data from the google spreadsheet. But There is one problem I don't know why only my first div is getting target via JavaScript not the second one..
any Help and solution would apricated..
Why My Second Line Targeting div id="load1" is not executing ????
Code.gs
`function loadDetails(id){
var ss = SpreadsheetApp.openById("14RM_170AefKbQq82NXAdSOemQLyAGcv_BTwYWd1-qtM")
var ws = ss.getSheetByName("Data")
var data = ws.getDataRange().getValues()
for(var i=0; i<data.length; i++){
var row = data[i]
if(row[0]== id){
password = {
psd: row[1],
id: row[0]
}
}
}
if(row[0]!= id){
password = "not found"
}
return password;
}`
Dashboard.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Hey this is other Employee Dashboard</h1>
<p>Your Employee Id: = </p>
<p>Your Password : = </P>
<div id="load">
<div>
<div id="load1">
<div>
<script>
window.onload = function(){
var id = "MN00018"
google.script.run.withSuccessHandler(function(output){
document.getElementById("load").innerHTML = `passing objects are ${output.psd} & ${output.id}`
document.getElementById("load1").innerHTML = `passing objects are ${output.id}`
}).loadDetails(id)
}
</script>
</body>
</html>
If you are actually testing your showing script, I think that there are 2 modification points.
HTML & Javascript side:
The tag of div is not enclosed. How about modifying as follows?
From:
<div id="load">
<div>
<div id="load1">
<div>
To:
<div id="load">
</div>
<div id="load1">
</div>
I think that this is the reason of your issue of Why My Second Line Targeting div id="load1" is not executing ????.
Google Apps Script side:
At Google Apps Script side, by if(row[0]!= id){password = "not found"}, even when id is found from the column "A", "not found" is returned. How about modifying as follows?
Modified script:
function loadDetails(id) {
var ss = SpreadsheetApp.openById("###");
var ws = ss.getSheetByName("Data")
var data = ws.getDataRange().getValues()
var password = {psd: "", id: ""};
for (var i = 0; i < data.length; i++) {
var row = data[i]
if (row[0] == id) {
password = {
psd: row[1],
id: row[0]
}
break;
}
}
return password;
}

How to parse date format, without access to source code

{$userinfo.create_account_date}
This returns me date in the following format: Oct-3-2017
I want to parse it to: DD/MM/YYY (03/10/2017)
The source code is encrypted. Is there a way to parse it through front-end only?
Front-end, assuming JavaScript. In most simple style.
function reformatDate(datumStr) {
var monthsArr = [];
monthsArr['Jan'] = '01';
// add missing months here
monthsArr['Oct'] = '10';
var dArr = datumStr.split('-');
return [dArr[1], monthsArr[dArr[0]], dArr[2]].join('/');
}
console.log(reformatDate('Oct-3-2017'));
Output:
3/10/2017
Addition to Karen's comment below.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function reformatDate(datumStr) {
var monthsArr = [];
monthsArr['Jan'] = '01';
// add missing months here
monthsArr['Oct'] = '10';
var dArr = datumStr.split('-');
return [dArr[1], monthsArr[dArr[0]], dArr[2]].join('/');
}
function elRfr(idName, datumStr) {
var id = document.getElementById(idName);
id.innerHTML = reformatDate(datumStr);
}
</script>
</head>
<body>
<div id="ourDate"><script type="text/javascript">elRfr('ourDate', 'Oct-3-2017');</script></div>
</body>
</html>
Karen, this is simplified example with just one DIV. In your case you should replace 'Oct-3-2017' with {$userinfo.create_account_date}, I guess.
If I assume correctly that your code is Salesforce Apex code.
Create a new var, initialize the date string as a new Date:
var d = new Date('Oct-3-2017');
Then manipulate it however you want with Date methods.

How to use an element property to pass a variable from Javascript

I'm attempting to send emails using an HTML template.
I've looked at this post:
(https://stackoverflow.com/questions/33178702/passing-variables-into-html-code)
Would either of the two code examples be close to something that could work to pass the variables from the Javascript to the HTML template?
My javascript variables are named detail2, detail3, detail4, detail5 and detail6.
1st attempt:
<html>
<head>
<script>
{
var detail2 = document.getElementById("detail2").innerHTML;
var detail3 = document.getElementById("detail3").innerHTML;
var detail4 = document.getElementById("detail4").innerHTML;
var detail5 = document.getElementById("detail5").innerHTML;
var detail6 = document.getElementById("detail6").innerHTML;
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
2nd attempt:
<html>
<head>
<script>
{
<input type="hidden" id="Detail2" value="detail2" />
<input type="hidden" id="Detail3" value="detail3" />
<input type="hidden" id="Detail4" value="detail4" />
<input type="hidden" id="Detail5" value="detail5" />
<input type="hidden" id="Detail6" value="detail6" />
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
Finally, the method given on GAS Dev is below, but this only confuses me more. I am sure I've been at this too long and I'm burned out, I just can't seem to see the answer on this one.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
If anyone can help it's much appreciated!
Below is the Javascript from the .gs script file.
function SendEmail() {
// initialize data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
// iteration loop
for (var i = 1; i<values.length; i++) {
// current times for comparator
var month = new Date().getMonth(); // returns today as 0-11 -- Jan is 0
var day = new Date().getDate(); // returns today as 1-31
var hour = new Date().getHours(); // returns today as 0-23
var minute = new Date().getMinutes(); // returns today as 0-59
// pull data from spreadsheet rows
var company = values[i][0];
var rating = values[i][1];
var detail1 = values[i][2];
var detail2 = values[i][3];
var detail3 = values[i][4];
var detail4 = values[i][5];
var detail5 = values[i][6];
var sendTime = values[i][7];
// character send times for comparator
var cSendMonth = sendTime.getMonth(); // returns sendMonth as 0-11 -- Jan is 0
var cSendDay = sendTime.getDate(); // returns sendDay as 1-31
var cSendHour = sendTime.getHours(); // returns sendHour as 0-23
var cSendMinute = sendTime.getMinutes(); // returns sendMinute as 0-59
// comparator
if(cSendMonth == month) {
if(cSendDay == day) {
if(cSendHour == hour) {
if(cSendMinute == minute) {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Test Email markup2 - ' + new Date(),
htmlBody: htmlBody,
});
} // end if minute test
}// end if hour test
}// end if day test
}// end if month test
}// end for loop
}
Can you try:
<html>
<head>
<script>
(function() {
var detail2 = document.getElementById("detail2").innerHTML;
document.getElementById("detail2_val").innerHTML = detail2;
})();
</script>
</head>
<body>
<p>
<br>"Punctual?" <span id="detail2_val"></span><br>
</p>
</body>
</html>
Currently, this line:
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
will not evaluate a template.
The method being used is:
createHtmlOutputFromFile('mail_template')
HtmlService has quite a few methods for creating html content. You need to use:
HtmlService.createTemplateFromFile(filename).evaluate()
There are some possible things that could go wrong in your overall work flow. If the situation is one in which you are writing data, and then immediately trying to read that same data that was just written, there could be a problem with the new data not being available to be read in such a short time span.
I would use:
SpreadsheetApp.flush();
immediately after writing the new data, and before creating the template.
Only your third html example has code for a template. To retrieve data and put it into a template, a scriptlet must either run a function, that then retrieves the data, or the data must be in global variables. The situation with global variable makes no sense, because you are using dynamic data, so a function would need to run to first put the data into a global variable. The function might as well just return the data directly. So, your scriptlet will probably need to run a server side function and return text or HTML to the html template. You probably need to use a printing scriptlet.
Apps Script documentation - force printing scriptlets

D3 collapsible trees without flare.json

I am trying to integrate a collapsible tree with a visualization tool :
http://bl.ocks.org/robschmuecker/7880033
Can someone please tell me how to make this code run without a flare.json file. I have the data in json format and I need to use that json output to make this code run. The code I have that converts a string into a json format is as follows:
<html>
<body>
<script>
//example dat
var str = "Charles Johnson\t4184\nCharles Johnson-Donald Williams\t8385\nCharles Johnson-Donald Williams-Daniel Fertig\t428\nCharles Johnson-Donald Williams-Daniel Fertig-Lino Walling\t1091\nCharles Johnson-Donald Williams-Daniel Fertig-Lino Walling-Jim Cooke\t318";
var lines = str.split("\n");
var name_ = lines[0].split("\t")[0];
var val_ = lines[0].split("\t")[1];
//alert(val_);
var obj = {name: name_,
children: [],
value: val_};
//process all lines
for (var i=1;i<lines.length;i++) {
var addr = lines[i].split("\t")[0].split("-");
var val = lines[i].split("\t")[1];
//alert(val);
var local_obj = obj;
var recursive_obj;
//alert(addr.length);
for (var j=1;j<addr.length;j++) {
recursive_obj = null;
for (var k=0;k<local_obj.children.length;k++) { //Doest get used for first instance
if (local_obj.children[k].name==addr[j]) {
recursive_obj=local_obj.children[k];
}
}
if (recursive_obj==null) {
recursive_obj = {name: addr[j],
children: [],
value: null
};
local_obj.children.push(recursive_obj);
}
local_obj=recursive_obj;
}
recursive_obj.value=val;
}
//print a json result
alert(JSON.stringify(obj));
</script>
</body>
</html>
This code converts the string into Json Format. Can someone please help me out in using this code instead of
treeJSON = d3.json("flare.json", function(error, treeData){}
and making the collapsible tree run. I would be very grateful if someone can assist me with this. Thank you :)
Best Regards
Mohd
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="try.js"></script>
<body>
<div id="tree-container"></div>
</body>
</html>
Right now you have obj, which is already an object, similar to what treeData needs to be inside the callback to the d3.json function. You can take everything out of that function, converting from this:
d3.json("flare.json", function(error, treeData){
//Do some stuff with treeData
})
to this:
var treeData = obj;
//Do some stuff with treeData;
Working fiddle: fiddle

How to get the description of a news Item from GOOGLE AJAX Feed API

I am using a script to load news from different sources, using Google AJAX feed API. How can I get the description of an entry? Below is an hello world program:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://news.google.com/?output=rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="feed"></div>
</body>
</html>
How can I get the description using the entry object??? I am using the google URL - http://news.google.com/?output=rss for RSS feeds in XML format. I want the "Description" part. How can I get that
You can get the description, but you can't use the JSON format and the entry object to do it. If you read the feed parameters at https://developers.google.com/feed/v1/devguide carefully, you'll see that description is not a field it returns at the entry level - just at the feed level.
To do it, you need to request the feed in XML format, and then load the individual nodes, including description. Here's the relevant snippet I've used to do it - change the formatting etc. as you need.
function initialize() {
var feed = new google.feeds.Feed("http://myblog.com/blog/feed/");
feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
feed.load(function(result) {
if (!result.error) {
var items = result.xmlDocument.getElementsByTagName('item');
item = items[0];
//build each element
var title = document.createElement("h4");
title.innerHTML = item.getElementsByTagName('title')[0].firstChild.nodeValue;
var content = document.createElement("p");
content.innerHTML = item.getElementsByTagName('description')[0].firstChild.nodeValue;
href = item.getElementsByTagName('link')[0].firstChild.nodeValue;
}
The HTML description can be retrieved by using the content variable.
Thus you should have:
div.appendChild(document.createTextNode(entry.content));
Be aware that this will retrieve HTML data format.
After much digging, I found that the Google API uses "contentSnippet" instead of description. No XML formatting needed.
function initialize() {
var feed = new google.feeds.Feed("http://myblog.com/blog/feed/");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
$(document).ready(function(){
$('#feed-pull').append('<ul></ul>');
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var desc = entry.contentSnippet;
Change entry.title in:
div.appendChild(document.createTextNode(entry.title));
to entry.description.

Categories

Resources