How can I access a public Google Drive file by XHR

2019-03-20 13:37发布

问题:

I need a HTML page to access Google Drive files with XMLHttpRequest (XHR) in Javascript without authentication (so my users don't have to be signed in with or have a Google account). These files have permission "Anyone with link". Since these files are open for the world (having the link) I don't see why it would be a problem to allow Cross-origin resource sharing (CORS) for them.

The downloadUrl requires authentication, so I guess that isn't a viable option. I have also looked at the webViewLink, which I guess requires the files to be "Public on the web" - turning up in search engines, etc, I guess. The is not a viable option for me either. I need the "Anyone with link" permission for these files. The most promising link is the webContentLink, which according to http://googleappsdeveloper.blogspot.se/2012/08/5-things-you-didnt-know-you-could-do.html allow public and unauthenticated access.

The problem I have with webContentLink is that it doesn't seem to be CORS friendly. My attempts with XHR in Chrome fail (quite silently). I don't add any headers.

My attempts with curl using --header "Origin: http://www.hello.se" and both with and without --header "Access-Control-Request-Method: GET" results in a HTTP/1.1 302 Moved Temporarily redirect to a short-lived content URL. The problem is that the redirect response has no signs of an Access-Control-Allow-Origin header, which is needed to enable CORS.

Is there anything I can do differently to get this to work?

Otherwise Google SDK team, can you make make the webContentLink CORS friendly for public files (which don't need cookie authentication), please?

回答1:

JSONP seems to be the only way to dynamically fetch google sheets from the client :

1) In Google Drive, Publish on the web the document & set sharing options to Public

2) Export your data in JSON format with a JSON type link, it will look like : "http://spreadsheets.google.com/feeds/list/YOUR_FILE_ID/od6/public/values?alt=json&callback=myCallback". You need to append &callback=myCallback to use JSONP. You can use jQuery to make your JSONP call.

3) Define a window.myCallback JS function to use the data



回答2:

You could try using the JS Google API client. It gets around the CORS restriction by downloading a proxy iframe.