ReferenceError: "document" is not defined - javascript

Im new to JavaScript and even more new to Google Apps Script. Im trying a simple function that shows the current date (only day, month e and full year), but the Google Script show the error ReferenceError: "document" is not defined.
My goal is to use this function in a Google Site. Here is the code:
function Data()
{
var d=new Date();
var dia=d.getDate();
var mes=d.getMonth();
var ano=d.getFullYear();
var DataCompleta=dia + "/" + mes + "/" + ano
document.write(DataCompleta);
}

Code running as a Google Apps Script does not run in the browser, so you cannot use web browser APIs with it. If you want to output content to a Google Site, then you need to use the API for Sites.
Presumably you would want something like createWebPage and then use the methods on the resulting object to add the content to it.

As said in the former answer you can't execute a function directly in the Browser, you'll have to choose a so called 'container' to run your function from it. I would recommand you read the documentation and maybe try a few simple tutorials to see how GAS can be executed.
EDIT : following your comments, feel free to have a look at this script built with UiApp, the result is viewable here and shows what you wanted to : "Hello, today is 25/10/2012"

Related

add Office.onReady() function to javascript

I am new to Javascript and am trying to make an outlook web-addin take the Office.onReady() function properly.
https://learn.microsoft.com/en-us/office/dev/add-ins/develop/initialize-add-in
I tried using
Office.onReady()
.then
to make my function work with the office js API but it then I got an error that my function couldn't be found.
Code:
$("#brief-summary").click(briefsummary);
$("#email-setup").click(emailsetup);
Office.onReady()
.then(function briefsummary() {
var msgFrom = Office.context.mailbox.item.from;
var msgfirstname = String(msgFrom.displayName).split(" ");
Office.context.mailbox.item.displayReplyAllFormAsync(
"Hello " +
msgfirstname[0] +
", <br> \
<br> Here is a brief summary on everything worked on: \
<br> \
<br>Thank you for your time, \
<br>"
);
});
Result:
Uncaught ReferenceError: briefsummary is not defined
So I am pretty sure I am doing it wrong.
I also tried using Office.onReady(); at the begining of the script. It suppressed the Uncaught Error: Office.js has not fully loaded. Your app must call "Office.onReady()" error but office javascript doesn't do anything. (Its suppose to bring up a new reply window with text inside)
Link to where the app is hosted: https://alloyautomateaddinbeta3.azurewebsites.net/index.html (Although the office.js only loads when you are in the outlook app. But you can go to sources from inspector in chrome and look at the js script in full)
Any ideas would be awesome.
I have seems to figure out what to do but I was pretty janky. If anyone knowas a better way to clean this up let me know.
I essentially my code inbetween this and it worked:
Office.onReady((info) => {
if (info.host === Office.HostType.Outlook) {
#Insert code here
}
});
It was pretty janky as it gives me a warning saying Function variables should not be placed in blocks. Use a function expression or move the statement to the top of the outer function
I will be working on the code periodically so I will update my answer to a better one as time goes on unless someone else has an answer as well.
Thanks

Error when running Youtube Data Service in App Scripts (js) – Daily Limit for Unauthenticated Use Exceeded

I'm running a custom function in App Scripts which utilizes the Youtube (YouTube Data API v3) advanced service. When running, I get the following error:
GoogleJsonResponseException: API call to youtube.videos.list failed with error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup. (line 15).
I'm not sure how to authenticate my application. I've added it to a cloud project and enabled the API's.
Update: Here's what my code looks like:
function getYoutubeData(youtubeId) {
// Don't run on empty
if(!youtubeId){return null}
// Make the request
var vidData = YouTube.Videos.list("statistics, snippet", {id: youtubeId}).items;
if (!vidData|vidData.length<1){return null}
// Get the first item
vidData = vidData[0];
return vidData.statistics
}
I believe your goal as follows.
You want to put the value of vidData.statistics in your script to the cell.
You want to achieve this using custom function like =getYoutubeData(youtubeId).
For this, how about this answer?
Issue and workaround:
Unfortunately, when YouTube Data API of Advanced Google services is used in the custom function, the access token is not used. From your script, I think that the reason of your issue is this. For example, when the function of const sample = () => ScriptApp.getOAuthToken(); is used as the custom function like =sample(), no value is returned. I think that this is the current specification of Google side because of the security.
In order to achieve your goal under above situation, how about the following workarounds?
Workaround 1:
In this workaround, at first, the youtube ID is set to the cells in Google Spreadsheet. And the value of vidData.statistics are retrieved by the Google Apps Script which is not the custom function and replace the youtube ID with the result values.
Sample script:
Please set the range of cells of youtube IDs to sourceRange and the sheet name. At the sample, it supposes that the youtube IDs are put to the cells "A1:A10". And please run getYoutubeData() at the script editor. Of course, you can also set this to the custom menu.
function getYoutubeData() {
const sourceRange = "A1:A10"; // Please set the range of cells of youtube IDs.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set the sheet name.
const range = sheet.getRange(sourceRange);
const youtubeIds = range.getValues();
const values = youtubeIds.map(([youtubeId]) => {
// This is your script.
if(!youtubeId){return [null]}
var vidData = YouTube.Videos.list("statistics, snippet", {id: youtubeId}).items;
if (!vidData|vidData.length<1){return [null]}
vidData = vidData[0];
return [JSON.stringify(vidData.statistics)];
});
range.setValues(values);
}
Workaround 2:
In this workaround, the custom function is used. But, in this case, the Web Apps is used as the wrapper. By this, the authorization process is done at the Web Apps. So the custom function can be run without the authorization. Please do the following flow.
1. Prepare script.
When your script is used, it becomes as follows. Please copy and paste the following script to the script editor.
Sample script:
// This is your script.
function getYoutubeData_forWebApps(youtubeId) {
// Don't run on empty
if(!youtubeId){return null}
// Make the request
var vidData = YouTube.Videos.list("statistics, snippet", {id: youtubeId}).items;
if (!vidData|vidData.length<1){return null}
// Get the first item
vidData = vidData[0];
return vidData.statistics
}
// Web Apps using as the wrapper.
function doGet(e) {
const res = getYoutubeData_forWebApps(e.parameter.youtubeId)
return ContentService.createTextOutput(JSON.stringify(res));
}
// This is used as the custom function.
function getYoutubeData(youtubeId) {
const url = "https://script.google.com/macros/s/###/exec?youtubeId=" + youtubeId; // Please set the URL of Web Apps after you set the Web Apps.
return UrlFetchApp.fetch(url).getContentText();
}
2. Deploy Web Apps.
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
By this, the script is run as the owner.
Select "Anyone, even anonymous" for "Who has access to the app:".
In this case, no access token is required to be request. I think that I recommend this setting for testing this workaround.
Of course, you can also use the access token. But, in this case, when the access token is used, this sample script cannot be directly used as the custom function.
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Click "OK".
Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
Please set the URL of https://script.google.com/macros/s/###/exec to url of above script. And please redeploy Web Apps. By this, the latest script is reflected to the Web Apps. So please be careful this.
4. Test this workaround.
Please put =getYoutubeData("###youtubeId###") to a cell. By this, the youtube ID is sent to the Web Apps and the Web Apps returns the values of vidData.statistics.
Note:
These are the simple sample scripts for explaining the workarounds. So when you use this, please modify it for your actual situation.
References:
Custom Functions in Google Sheets
Web Apps
Taking advantage of Web Apps with Google Apps Script

How to access call logs in android using Cordova?

I want to access recent call logs using Cordova but there is no official plugin for that, some guy made a custom plugin for that https://github.com/dalyc/Cordova-CallLog-Plugin is the only hope for me, but the problem is this plugin is no longer supported by its creator and it is using AngularJS in his example. I did my search work and found that People tried to use this plugin to use with javascript but they got no working solution. As the author mentioned here https://github.com/dalyc/Cordova-CallLog-Plugin/issues/4 there are 3 functions that will work with javascript.
window.plugins.calllog.list : get recent calls - takes a day limit e.g 7 is go back a week
window.plugins.calllog.show : show contact for specified phone number
window.plugins.calllog.contact : get contact details for specified phone number
I tried each of them and apparently window.plugins.calllog.show is working fine and it is showing contact for specific numbers. But window.plugins.calllog.list did not worked for me it is returning "undefined". Need help please. Thanks in advance.
my index.html contains
<button id="call_log" onclick="loadLogs();">call log</button>
my app.js contains
//calllog
function loadLogs() {
if(window.plugins.calllog == "undefined"){
alert("Doesn't works");
}
else
{
alert("works");
window.plugins.calllog.show('12345');
//this code is working and opening list of contacts having these "12345" in their phonenumber
var list = window.plugins.calllog.list('7');
alert(list[0]);
}
}
Uncaught TypeError: Cannot read property '0' of undefined
Here is a plugin I have made
https://www.npmjs.com/package/callsplugin
you basically have to write the command
cordova plugin add callsplugin
and follow the instruction you find in the project site

What are these Google-calendar events from?

It seems it's fairly common practice to grab the contents of a Google-calendar embed code, and add a stylesheet into it (either manually or through something like a PHP script) and display a custom-styled public calendar.
The odd thing is, I noticed if you click the print button at the top, or the "Google Calendar" in the lower right, it goes to localhost or whatever domain the page is - not the Google calendar.
If you try to trace the "gcal$func$[3]();" onclick through the Chrome devtools, or through Firefox with gcal$func$[3].toSource(); it will not find it or say
"function () {
[native code]
}"
So where is this function coming from, and how can you tweak this to make it open in a new window with the Google url, not the current domain (404)?
According to the Google Calendar embed JS code, the function points to the following code
window.open(Pf(this.c.i.Nb + "/render", "cid", b))
this.c.i.Nb represents the base URL, which is by default the domain where the script runs (in your case that's your domain). However, it's intended to be google.com domain and fortunately, it's very easy to change that. baseURL is one of the parameters in the initialization script (declared in the page you're grabbing) and you just need to configure that to https://www.google.com.
If you use PHP, your code might look like this.
$page = new DOMDocument("1.0", "utf-8");
// grab the Google Calendar code
$page->loadHTMLfile("https://www.google.com/calendar/embed?src=yourcalendar%40gmail.com");
// set up the baseUrl and print the grabbed page
echo str_replace('"baseUrl":"/"', '"baseUrl":"https://www.google.com/"', $page->saveHTML());
Now all the links should work correctly.

How to completely read a site that contains javascript from an android service?

I'm trying to read a node from a website that contains java script.
In VB .NET I just use the following code:
Dim listSpan As IHTMLElementCollection = bodyel.getElementsByTagName("span")
For Each spanItem As IHTMLElement In listSpan
If spanItem.className & "" = "span_name" Then
If Not spanItem.innerText Is Nothing Then
str_result = spanItem.innerText.ToString
Console.WriteLine("Found it: " & str_result)
Else
str_result = "NO"
Console.WriteLine("Not Found")
Console.Beep(500, 500)
End If
End If
Next
But I just can't find a way to convert this code to work in Android service. (Java).
I tried Jsoup but Jsoup is only reading the "view source code" elements and not the javascript results as html.
try {
Document doc = Jsoup.connect(str_link).get();
Elements links = doc.select("span_name");
for(Element link : links) {
String result = link.text();
Log.d("TMA Service","result: " + result);
list.add(title);
}
I mean. This code in VB can find everything. (just like if I right click in an element using google chrome and select "Inspect Element". This shows everything and I'd like to know how to get this data with Android.
CAN SOME ONE GIVE ME AN EXAMPLE?
Thanks.
Unfortunately you can't handle Javascript and dynamic content with Jsoup. Please see my answer here for more information and some examples of Java libraries, that may help you here.
Edit:
HtmlUnit - Getting started (section Getting started)
HtmlUnit: A Simple Example: Check Yahoo Email
How to use HtmlUnit in Java?
HtmlUnit: A Quick Introduction
HtmlUnit – A quick introduction
Getting started with HtmlUnit

Categories

Resources