I try to acces google drive in a wordpress theme and get the following error while downloading a selected file.
XMLHttpRequest cannot load https://drive.google.com/a/mobfish.net/file/d/0B5IETzPj-JCw832h9rdwk/view?usp=drive_web. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://wptest.dev' is therefore not allowed access.
(I modified the URL a little bit, this is not the real file ID)
Here is the JavaScript Code:
var developerKey = document.getElementById('key').innerHTML;
var clientId = document.getElementById('clientID').innerHTML;
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/drive.readonly'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
gapi.load("client");
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView(google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
.setIncludeFolders(true)
.setSelectFolderEnabled(true);
var picker = new google.picker.PickerBuilder().
hideTitleBar().
disableFeature(google.picker.Feature.NAV_HIDDEN).
addView(view).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data.action == google.picker.Action.PICKED) {
var file = data.docs[0];
download(file);
}
}
function download(file) {
console.log("downloading " + file.id);
console.log(file);
var downloadUrl;
if (file.url) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.url);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}
function callback(param) {
console.log(param);
}
Maybe i just forget to add some settings at https://console.developers.google.com ? Thanks in advance, regards.