尝试在浏览器中使用Gmail的API来发送电子邮件。 我已经设置了带有相关密钥和OAuth详细信息的Google API项目,并且还“允许”了我的托管域。
JavaScript看起来像这样:
var clientId = 'XXX';
var apiKey = 'XXX';
var scopes = 'https://www.googleapis.com/auth/gmail.send';
function onGoogleAPILoaded () {
console.log('onGoogleAPILoaded');
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}
function checkAuth () {
console.log('checkAuth');
gapi.auth.authorize({client_id:clientId, scope:scopes, immediate: false}, handleAuthResult);
}
function handleAuthResult (authResult) {
console.log('handleAuthResult');
console.log(authResult);
if(authResult && !authResult.error) {
loadGmailApi();
}
}
function loadGmailApi () {
console.log('loadGmailApi');
gapi.client.load('gmail', 'v1', sendEmail);
}
function sendEmail () {
console.log('sendEmail');
sendMessage({'To':'XX@XX.com', 'Subject':'Testing'}, 'Hello', sendEmailComplete);
return false;
}
function sendEmailComplete () {
console.log('sendEmailComplete');
}
function sendMessage (headers_obj, message, callback) {
console.log('sendMessage');
var email = '';
for(var header in headers_obj) {
email += header += ": "+headers_obj[header]+"\r\n";
email += "\r\n" + message;
}
var sendRequest = gapi.client.gmail.users.messages.send({'userId': 'me', 'resource': {'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')}});
return sendRequest.execute(callback);
}
我的浏览器控制台显示如下:
onGoogleAPILoaded
checkAuth
handleAuthResult
{error:“ popup_blocked_by_browser”,...}
未捕获的DOMException:阻止了源为“ https://accounts.google.com”的帧访问跨域帧。
有什么想法为什么我在使用合法的Google API时会遇到起源政策问题?