Trying to post url segment to firebase - javascript

I am running a script on a public webpage and i want to post part of the url into firebase.
I can insert a button that retrieves the url segment as a string variable but I can't post automatically to firebase from the open page because of permissions. Is there any way to do this other than creating an external page and posting the variable manually? Here is the Script I am using. This runs fine in external pages but i want to run it from the public page.
function pushit() {
firebase.initializeApp(config);
var url = location.href;
var filename = url.substr(38, 8);
console.log("Push Successfull!!!");
var database = firebase.database();
var ref = database.ref('url/data'); var data = {url: filename }
ref.push(data);
}
The error get is:
Uncaught ReferenceError: pushit is not defined
at HTMLButtonElement.onclick (index.html)

I created a popup window instead, which sends the data to the Firebase. I realized that running this sort of code in other websites was not possible.

Related

Retrieve URL of AppScript using Javascript

I am trying to reload the current page with a new parameter, but I am unable to retrieve the correct URL of the webpage. I am getting an alternate URL instead of the one that triggers the web app
https://script.google.com/a/user/macros/s/A...ljhGC/dev?action=menu&id=1
when the button is clicked I want the action parameter's value to change and the page to reload as
https://script.google.com/a/user/macros/s/A...ljhGC/dev?action=checkout&id=1
Here is my javascript within the HTML File
console.log(document.url);
var url = new URL(window.location.href);
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
search_params.set('action', 'checkout');
url.search = search_params.toString();
var new_url = url.toString();
window.location.replace(new_url);
console.log(new_url);
}
This is the URL that gets logged
https://n-ikwx...khq-1lu-script.googleusercontent.com/userCodeAppPanel?action=checkout
How do I retrieve the actual URL that is in the address bar?
Thanks in advance!
Issue:
A iframe with different origin cannot read the href property of location of the the parent/top frame, which is write only. So, You can't.
Solution:
You can however pass the url from server side.
Server side:
function getTopUrl(){
return ScriptApp.getService().getUrl();
}
Client side:
var topUrl;
function getTop(){
google.script.run.withSuccessHandler((url)=>{topUrl=url;}).getTopUrl();
}
window.addEventListener('load', getTop);
References:
Where is my iframe in the published web application/sidebar?
Same origin policy
Service#getUrl
google.script#run

How to get a direct download URL from Google Picker JavaScript API?

I'm trying to get a direct download URL for a file using Google's Picker API so that I can choose a file and pass this URL to server side code to download and store a copy of the item on the server.
I'm able to authorize through the picker API and get info of a picked file including the file name and preview URL (which is confusingly referred to as simply "A URL to this item" in the JSON response docs: https://developers.google.com/picker/docs/results)
I noticed that there is a post about using the Drive API to get a direct download URL here: Get google drive file download URL
However when I do this in my picker callback function (based on the docs here: https://developers.google.com/picker/docs/)
I get an error of:
"Project [number here] is not found and cannot be used for API calls. If it is recently created, enable Drive API by visiting https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=[project number here] then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
I have the API enabled in my developer console and the URL added to the JS allowed origins.
The documentation is very confusing and there seems to be 3 versions of the REST API to use with Drive which is based on an gapi.auth2 object whereas the picker api uses gapi.auth object.
I'm not sure if I need to authenticate again using the Google Drive API before performing the GET request. This all seems very messy and I believe there must be an easier approach for what is a simple request!
My picker callback function:
pickerCallback: function(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var fileName = doc[google.picker.Document.NAME];
var url = doc[google.picker.Document.URL];
var docId = doc[google.picker.Document.ID];
var request = null;
gapi.client.load('drive', 'v2', function() {
request = gapi.client.drive.files.get({
'fileId': docId
});
request.execute(function(resp){
console.log(resp);
});
});
//Write upload details to page
//Populate hidden field
}
Developer console screen - The first app is the picker API the second is for the Drive API:
You may want to try the simple callback implementation shown in this documentation. Notice that url was initialized before the if statement:
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'You picked: ' + url;
document.getElementById('result').innerHTML = message;
}
Also, in authorizing, set the AppId value and choose the user account with the app's current OAuth 2.0 token. Note that the AppId set and the client ID used for authorizing access to a user's files must be contained in the same app. Then, after successfully obtaining the fileId, you can then send request using files.get. By default, this responds with a Files resource in the response body which includes downloadUrl.
For additional insights, see this related SO post.

Google Spreadsheet script, file access in Drive, "You do not have permission to call ..."

I have a Sheet where I need to get the id of a file located in my Google-drive.
I have written the folowing script:
function get_id_pdf() {
var nom='INV432-altaïr-Famille XXX-XXX Marie-03-2016.pdf';
var files = DriveApp.getFilesByName("'"+nom+"'");
while (files.hasNext()) {
var file = files.next();
var name = file.getName();
var type = file.getMimeType();
var url = file.getUrl();
var id = file.getId();
// Logger.log(file.getId());
return file.getId();
}
}
If I execute it in the Script editor (with the run button), it is working well (I get the id the the Log).
But If I call the script from a cell (in the cell: =get_id_pdf()) of my Google-Sheet, I get the error:
"You do not have permission to call getFilesByName" (see image)
I have of course all the authorization to access to this file (it is in my own drive, and the file havs been created by me).
Does somebody have an idea ?
Regards.
You cannot make calls to services that require user authorization as an anonymous user, which is what custom functions execute as. You will need to put the behavior into a custom menu, or a sidebar so that it can be authorized by the user.
Authorization Documentation
Custom Function Documentation
If your custom function throws the error message "You do not have
permission to call X service.", the service requires user authorization
and thus cannot be used in a custom function.

Lotus notes client link and browser link in xpages to download file stored in server directory

I have a Xpage in which there is a link to download the ics file which I have stored on server,As when the user clicks the link, the user is able to download the file name "votes.ics".
Accordingly when it is been accessed from browser, it allows me to download the file but at the same time when I want to download the same file using the link from LOTUS NOTES Client,It throws as an error Resource file not found it means the path in notes client has an issue,
To make it more clear, For example I have a database name "SMP_Intern.nsf" in the folder name "SMP" on the server and the onclick script behind the link is
var docId = getVotingDocumentUID();
if(docId != ""){
if(#ClientType() == "Notes"){
var path_private = "server_name/SMP/SMP_Intern.nsf";
var httpUrl = path_private.split("/")[0];
var databaseUrl = (httpUrl+"!!"+path_private.split("/")[1]+"/"+path_private.split("/")[2]);
var url = "/xsp/"+databaseUrl+"/.ibmmodres/domino/OpenAttachment/"+databaseUrl+"/"+docId+"/ics_file/votes.ics";
return url;
}else{
var url = "/0/"+docId+"/$File/"+"votes"+".ics?OpenElement";
return url;
}
}else return false;
For the notes client it goes to 'if' condition and gives error resource not found,but when it is browser the 'else' condition works perfectly fine.
Both the paths are same basically but could not able to find the mistake.
Any suggestion will be helpful.
You don't need a special treatment for Notes Client (XPiNC) in this case.
Your SSJS code for link value
var url = "/0/"+docId+"/$File/"+"votes"+".ics?OpenElement";
return url;
works for XPiNC too as the attachment is in the current database:
If current database resides on server then the URL points to the attachment on server.
If current database is a local replica then the URL points to the attachment in local database on client.
Have you tried #URLOpen( urlstring )formula for opening from client ?
The url must be a complete url http://DominoServer/DBPath/0/DocUNID/$file/filename
var url = "http://"+path_private +"/0/"+docId+"/$File/"+"votes"+".ics?OpenElement";
#URLOpen( url );

Deleting Parse files

If I have a Parse object with a file attribute on it and then I delete the original object.
Does it delete the orphaned file?
If not, how do I delete the file?
I'm doing everything in cloud code using Javascript trying to put an "After delete" function together and cascading the delete down.
EDIT
OK, a quick test later. The files are not deleted. They are orphaned. So, how to delete the file in cloud code?
Another option is pressing the clean up button located in the settings page of your app (I saw that somebody else had mentioned deleting via the REST API).
You can delete files that are referenced by objects using the REST API. You will need to provide the master key in order to be allowed to delete a file.
If your files are not referenced by any object in your app, it is not possible to delete them through the REST API. You may request a cleanup of unused files in your app's Settings page. Keep in mind that doing so may break functionality which depended on accessing unreferenced files through their URL property. Files that are currently associated with an object will not be affected.
There is a REST API for that, see here
Other answers already pointed out the proper links... The following shows how I did it from within the browser...
// 1. in a browser console, go to their domain do avoid cross-domain failure later
// (paste this by itself)
document.location.href='https://api.parse.com';
// 2. load up jquery
// (paste this and the rest of the script into the console only after the page url above loads)
(function(){
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
})();
// the goods
function deleteParseFile(appId, masterKey, filename)
{
var serverUrl = 'https://api.parse.com/1/files/' + filename;
$.ajax({
type: "DELETE",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", appId);
request.setRequestHeader("X-Parse-Master-Key", masterKey);
},
url: serverUrl,
success: function(results) {
console.log('success:', results)
}, error: function(error) {
console.log('error:', error);
}
});
}
// 3. set the file you want deleted... and delete it
var appId = "<YOUR_APPLICATION_ID>";
var masterKey = "<YOUR_MASTER_KEY>";
// this filename can be found in the file object or the parse image URL
var filename = "tfss-abcd1234-dcba-4321-1a2b-112233aabbcc-my-file.gif";
deleteParseFile(appId, masterKey, filename);

Categories

Resources