I've read a lot of other people with half of this problem, and tried their solutions, but I can't get anywhere with it.
I first ran the example tutorials from google here:
https://campus.codeschool.com/courses/discover-drive/
Then I ran the example code from here:
https://developers.google.com/picker/docs/index
Running those codes with my API and client keys (I've even created new keys, tried using only the part before the .apps.googleusercontent.com for the client key as I've seen in some other example code, etc.) and I get the same result.
The page loads and asks for permission to access google drive for an account As soon as I give it permission it reverts to the following error:
Jconsole Error
I have a useless window error that says:
There was an error!
The API developer key is invalid.
Now Other people have said the error was normal, and that their code still worked. Mine on the other hand does not work, AND it gives me that error.
<script>
var clientId = '249642562982-8ss843cvik6r1rrm94i1kt5cf4jf201c.apps.googleusercontent.com';
var developerKey = 'AIzaSyBeDBmIqzCYCNvrpSwXcLz6ido_qGZL6sg';
var accessToken;
function onApiLoad() {
gapi.load('auth', authenticateWithGoogle);
gapi.load('picker');
}
function authenticateWithGoogle() {
window.gapi.auth.authorize({
'client_id': clientId,
'scope': ['https://www.googleapis.com/auth/drive']
}, handleAuthentication);
}
function handleAuthentication(result) {
if(result && !result.error) {
accessToken = result.access_token;
setupPicker();
}
}
function setupPicker() {
var picker = new google.picker.PickerBuilder()
.setOAuthToken(accessToken)
.setDeveloperKey(developerKey)
.addView(new google.picker.DocsUploadView())
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.setCallback(myCallback)
.build();
picker.setVisible(true);
}
function myCallback(data) {
if (data.action == google.picker.Action.PICKED) {
alert(data.docs[0].name);
} else if (data.action == google.picker.Action.CANCEL) {
alert('goodbye');
}
}
</script>
<script src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
Here are my keys
This is driving me nuts! It feels like I've tried everything and nothing is working. Why would google spend time to create a tutorial site, with full-on video lessons that check your code's validity if the flippin' resulting code doesn't work!? Take down the videos and example code if it is broken! I've wasted all day on this.
Can anyone help me figure out what's going on here?
References:
How to upload file on google drive from my website?
Using Google Drive in an iFrame doesn't work
Google Drive Picker - Developer Key is Invalid Error
Google Drive API OAuth 2.0; Error: origin_mismatch
I would recommend to use this example. I have also tested this example, it is working for me. You can edit the scope according to your requirements.
Related
I am currently writing a Google Apps Script inside a Google Sheet to read data from a list of spreadsheets (spreadsheet url is provided by the user). However, I cant seems to find a way to check if the url is valid or if user have access to the spreadsheet or not before calling SpreadsheetApp.openByUrl().
I have written the following code to "validate" the url:
for(int i = 0; i < urls.length; i++) {
let spreadsheet = null
try {
spreadsheet = SpreadsheetApp.openByUrl(urls[i]);
} catch (e) {
continue;
}
// Continue to do other stuff to read data from spreadsheet...
}
This however has an issue, it was able to catch the first few 'You do not have permission to access the requested document.' exception. But after a certain number of exception had occur, I would get a permenant error that cant be caught, stopping the script all together.
Is there a better way to do this?
Minimal reproducible example:
Create 3 google sheet using different google account
Using a different google account, create a google sheet and add the following code into Code.gs
function myFunction() {
// Put any 3 real spreadsheet url that you do not have access to
let urls = [
"https://docs.google.com/spreadsheets/d/1gOyEAz0amm4RghpE4B7f26okU3PG3vWZkrfiC-SBlbw/edit#gid=0",
"https://docs.google.com/spreadsheets/d/1Oia7ADu5BmYroUq1SLyDMHTJowrwSXOhCEyNO3nXmMA/edit#gid=0",
"https://docs.google.com/spreadsheets/d/1HE_IXURpBr_FJN--mwLo6k9gih07ZEtDGBqYSk6KgiA/edit#gid=0",
]
urls.forEach(url => {
try {
SpreadsheetApp.openByUrl(url)
} catch (e) {
console.log("Unable to open this spreadsheet")
}
})
}
function onOpen() {
SpreadsheetApp.getUi().createMenu("Test").addItem("myFunction", "myFunction").addToUi()
}
Run the function once in the apps script panel and authorize the application
Refresh this google sheet
Wait for the Custom Menus to show up and press "Menu" > "myFunction"
As you can see, the openByUrl() call is sitting inside the try catch block, however when you run the function through custom menu, you will still get "Error: You do not have permission to access the requested document.".
Executions Log:
From your question, I thought that your situation might be due to the specification or a bug of SpreadsheetApp.openByUrl. If my understanding is correct, in order to avoid this issue, how about putting the method for checking whether the file can be used before SpreadsheetApp? In your script, how about the following modification?
From :
SpreadsheetApp.openByUrl(url)
To:
var fileId = url.split("/")[5];
var file = DriveApp.getFileById(fileId);
spreadsheet = SpreadsheetApp.open(file);
In this modification, the file is retrieved with DriveApp.getFileById(fileId). When fileId cannot be used, an error occurs. But in this case, try-catch can be correctly worked. By this, the issue of SpreadsheetApp doesn't occur.
I have an issue where other uses of my Google apps script's url is getting changed. Due to this issue they are not able to open the html page.
Original url "https://script.google.com/a/macros/google.com/s/abcxyz-kaskasdb/exec?v=applyleave"
changed url "https://script.google.com/macros/s/abcxyz-kaskasdb/exec?v=applyleave"
I realize "/a" and "/google.com" is getting removed some how.
How can I fix this issue.
Here is my code that is rendered:-
function include(filename)
{
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function render(file,argsObject){
var tmp = HtmlService.createTemplateFromFile(file);
if(argsObject){
var keys = Object.keys(argsObject);
keys.forEach(function(key){
tmp[key] = argsObject[key];
});
}
return tmp.evaluate();
}
And here's the code for the server which should accept POST requests:
var Route = {};
Route.path = function (route,callback){
Route[route] = callback;
}
function doGet(e) {
Route.path("applyleave",leaveApply)
Route.path("leaveroster",leave_Roster)
if (Route[e.parameters.v]){
return Route[e.parameters.v]();}
else {
html = HtmlService.createTemplateFromFile('home');
return html.evaluate();
}
}
The error received from other side is this :-
Can anyone explain and provide solution?
There is nothing wrong with the deployment URL getting changed - it is common for Google to perform this redirection.
The issue is can be rather a permission issue. Make sure you deploy the WebApp as "Anyone, even anonymous".
However, currently I am experiencing the same behavior like you due to a multiply reported recent bug:
https://issuetracker.google.com/72798634
https://issuetracker.google.com/165350842
https://issuetracker.google.com/166010550
https://issuetracker.google.com/166320373
https://issuetracker.google.com/167692852
https://issuetracker.google.com/169349069
Please refer to this Github repo.
After the first deployment, you need to make further deployments on the same version by clicking on "Manage Deployment" and then selecting the version to "New version"
enter image description here
I've been playing around with the appscript web app thingy and thought I could use it for commercial purposes among a group of say 15 users. However, I get this sporadically:
In the incognito window on the top it works fine. It's logged in as the owner of the app which is me but not really me because I have another account for stuff like this. On the top, is my normal chrome which is logged in as me and as the owner of the account. This is how I set it up
And this is the sharing thing on the my projects
Finally, it draws from this google sheet which for now only I have access to, so hopefully that means no one else can access the data with permission which hopefully means anyone can open it but no one can get access to my precious data necessary to actually use the sheet unless they have access. Of course, in case I'm wrong I have to obscure the url. Anyway, how do I prevent this "Sorry, unable to open the file at this time" error which happens randomly.
It looks like what you are experiencing is an ongoing issue which many users have reported on Google Issue Tracker here and it stems from multiple accounts being logged in.
I suggest you star ★ the issue above and eventually add a comment saying that you are affected by it.
I use Firebase hosting, which has a free tier and is a Google product, for my website.
Go to your Firebase console when logged into a Google account:
https://console.firebase.google.com/?pli=1
I have minimal content in the Firebase index.html file, and then I load more content after the home page loads by using an AJAX POST call to Apps Script and return the content from Apps Script using the Content Service. I think that Firebase hosting is better than a Google Site. A Firebase hosting site requires some set up and some learning, so it's not as easy as Embedding an Apps Script Web App into a Google Site, but for the long term I think it's a better solution.
function doPost(e) {
try{
var html;
var fileName = "MyWebsite";
html = HtmlService.createTemplateFromFile(fileName).evaluate().getContent();
//Get the html file as a string
if (!html) {
html = '<div>There was an error</div>';
}
return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.TEXT);
}catch(e) {
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), "Load Error", e.message +
"\n\n" + e.stack);
html = '<div>There was an error</div>';
return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.TEXT);
}
}
In your index.html file you need to call the Web App:
window.getWebSiteContent = function() {
//console.log('getMainContent')
var payload,url;
url = "Put the Apps Script published Web App URL here";
//console.log('url: ' + url)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
//console.log('onreadystatechange')
if (this.readyState == 4 && this.status == 200) {
//console.log('this.responseText ' + this.responseText);
addTheMainContentToTheWebApp(this.responseText);//Run a function that adds the content
} else if (this.readyState == 4 && this.status !== 200) {
//console.log('Error',this.status)
}
};
xhttp.open("POST",url, true);
xhttp.setRequestHeader('Content-Type', 'text/plain');
payload = {data:{"keyName":"Value"}};
payload = JSON.stringify(payload);
//console.log('payload: ' + payload)
xhttp.send(payload);
}
document.addEventListener('DOMContentLoaded', function() {//Runs when the site is loaded
getWebSiteContent();
});
Here is my script, which basically iterate through drive folder, and put the file's blob as a attachment to some page on google site. It was working fine till day before yesterday, suddenly stop working after that.
function myFunction() {
var testpage = SitesApp.getSiteByUrl(siteURL).getChildByName("test");
var photofolder = DriveApp.getFolderById(folder_ID);
var filesinpf = photofolder.getFiles();
while(filesinpf.hasNext()){
var file = filesinpf.next();
var fblob = file.getBlob();
testpage.addHostedAttachment(fblob); //This line generating an error
}
}
Please help!
I had the same problem yesterday.
I have been working with this for a week, and yesterday I got an internal error in the last line:
function myFunction() {
var myFolder = DriveApp.getFolderById
("0B-ZOMOQnNEDOU9sWEV5SzlXVTQ");
var myFile =
myFolder.getFilesByName("Data.txt").next();
var myBlob = myFile.getBlob();
var myPage =
SitesApp.getSiteByUrl("https://sites.google.com/site/
demo ").getChildByName
("home/demoFileCabinet");
myPage.addHostedAttachment(myBlob);
}
Maybe a problem in Google Sites??. The code is correct.
I created an Issue Tracker too.
You can reproduce this error by using the sample code provided by google:
https://developers.google.com/apps-script/reference/sites/page#addHostedAttachment(BlobSource)
I created an enterprise support Ticket.
Keep you updated: [Case #14128120] Google Sites addHostedAttachment() not working
I got the following response from google:
Let me confirm that this is an issue on our end, filed with issue ID #68842220.
Please notice that our Engineering Team has already found the root cause for this.
At the moment, still, I can't confirm you when it will be fixed, but let me provide you with a simple workaround that will work while we wait for the fix: swap the "domain.com" and the "macros" parts of the URL when entering the URL in the dialog.
Sample, for url:
https://script.google.com/a/domain.com/macros/s/AKfycbwJfGpXIiWHfsCi-j66RuPMNx6kTFsdjYIbNOyufZptGA1tirm6/exec
try
https://script.google.com/a/macros/domain.com/s/AKfycbwJfGpXIiWHfsCi-j66RuPMNx6kTFsdjYIbNOyufZptGA1tirm6/exec
I have some google apps script code that adds Editors to a document with no problem. However, when I run the following code I find that some of the editors are removed, and some error with the following message: "Exception: We're sorry, a server error occurred. Please wait a bit and try again."
var file = DocsList.getFileById( fid );
var editors = file.getEditors();
for ( el = 0; el < editors.length ; el++ ) {
file.removeEditor( editors[ el ] );
}
Given that the editors are retrieved from the file itself, and then fail to be removed, I cannot see how to progress this, as the error message offers no help.
Has anyone experienced similar. I cannot see any issues raised against this.
Thanks in advance.
Chris
You could try to put your file.remove(editors[ el ]) in a try-catch structure to catch the error (and see it) and let your app finish in every case.
Example :
function myFunction() {
var file = DocsList.getFileById( '0AnqS........bW1DNnVBbVE' );
var editors = file.getEditors();
Logger.log(editors.join())
for ( el = 0; el < editors.length ; el++ ) {
try{
file.removeEditor( editors[ el ] );
Logger.log(editors[el]+' removed');// this editor is successfully removed
} catch(error)
{Logger.log('error on el = '+editors[el]+' = '+error)
}
}
}
This of course brings no answer on your issue but it could help to see what is happening in more details, which editor gets an error and which doesn't.
I have the same experience, both removeEditor and removeViewer can fail for some users, despite obtaining the user object from the getViewers or getEditors methods.
My observation is that unless the returned user object is a Google apps account holder then the remove action will fail.
So, on a google apps domain example.com a file might be shared with the following email addresses:
normal_account#example.com
group_account#example.com
third_party#some_other_example.com
removeEditor/removeViewer will only succeed for the first address on the list.
Although the call to getEditors/getViewers returns a list of user objects, some of the objects appear empty eg user.getEmail() returns a blank string, which is what the API documentation says will happen https://developers.google.com/apps-script/reference/drive/user#getEmail%28%29 if the email address is not available.