My app interacts with Google with JavaScript only. I want user to access their files list without login (access offline) after first time authentication. I tried many solutions available on stack or in google documentation. But Not able to get any solution. so I has uploaded the fresh running code. But this is asking the user for login every time when he is not logged in to gmail in browser.
My html is:
<button id="authorize-button" style="display: none;">Authorize</button>
<pre id="content"></pre>
My Script :
<script type="text/javascript">
var CLIENT_ID = '****************';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
var SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';
var authorizeButton = document.getElementById('authorize-button');
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
listFiles();
} else {
authorizeButton.style.display = 'block';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
function listFiles() {
gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
}).then(function(response) {
appendPre('Files:');
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendPre(file.name + ' (' + file.id + ')');
}
} else {
appendPre('No files found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
I also tried to user:
var auth2;
function init() {
alert('in init');
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
clientId: '**********************',
scope: 'https://www.google.com/m8/feeds https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appfolder'
});
});
$('#authorize-button').click(function() {
auth2.grantOfflineAccess({'redirect_uri' : 'postmessage', 'approval_prompt' : 'force'}).then(function(resp) {
console.log(resp);
var auth_code = resp.code;
});
});
}
Here I am able to access the response code. But how to use it for offline access. Please help me with some code. I also has tried almost all documentation and got very confused.