我正在开发Chrome扩展程序,并且遇到问题:
“未捕获的ReferenceError:gapi未定义”。
我正在将XML请求发送到gapi。它已加载,但是在使用gapi.auth2.authorize
函数时,会出现上述错误。
对此我是陌生的,想知道我做错了什么,或成功进行的方法。
background.js
var CLIENT_ID = "139751156265-mvroahocc1d4g7e848q44f1uqk0e78mc.apps.googleusercontent.com";
var SCOPES = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/spreadsheets',
'https://docs.google.com/feeds'
];
var x;
xhrWithAuth();
function xhrWithAuth() {
console.log("xhrWithAuth");
var access_token;
var retry = true;
getToken();
function getToken() {
chrome.identity.getAuthToken({
'interactive': true
}, function(token) {
if (chrome.runtime.lastError || !token) {
console.log('getAuthToken', chrome.runtime.lastError.message);
// callback(chrome.runtime.lastError);
return;
}
console.log(token);
x = new XMLHttpRequest();
x.open('GET', 'https://apis.google.com/js/client.js');
x.setRequestHeader('Authorization', 'Bearer ' + token);
x.onload = function() {
console.log(x.response);
};
x.send();
setTimeout(function() {
window.gapi_onload = checkAuth(token, x);
}, 5000);
});
}
};
function checkAuth(test, x) {
console.log("inside checkAuth", new Date());
gapi.auth2.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
function handleAuthResult(authResult) {
console.log("handleAuthResult", new Date());
}
manifest.json
{
"name": "Daca",
"version": "1.0",
"manifest_version": 2,
"description": "Update spreadsheet on user Submit",
"browser_action": { },
"background": {
"scripts": ["background.js"],
"persistent": true
},
"permissions": ["tabs", "[URL which I am using]", "https://apis.google.com/js/client.js", "https://accounts.google.com/o/oauth2/token", "identity", "https://content-sheets.googleapis.com/v4/spreadsheets/*"],
"content_scripts": [{
"matches": ["[URL which I am using]"],
"js": ["contentscript.js"],
"run_at": "document_start"
}],
"oauth2": {
"client_id": "[my client_ID]",
"scopes": [
"https://www.googleapis.com/auth/spreadsheets"
]
},
"content_security_policy": "script-src 'self' 'unsafe-eval' https://apis.google.com; object-src 'self'"
}
答案 0 :(得分:0)
虽然确实是使用XMLHttpRequest来获取gapi文件,但是仅获取它不会使它的代码可用。您必须将其加载到后台页面中。有几种方法可以做到这一点。例如:
不好的方法(使用eval
):
x.onload = function() {
if (x.status == 200) {
eval(x.response); //BAD WAY
//rest of code that uses gapi ...
}
};
更好的方式(使用<script>
标签):
x.onload = function() {
if (x.status == 200) {
var myScript = document.createElement('script');
myScript.innerHTML = x.response;
document.body.appendChild(myScript);
//rest of code that uses gapi...
}
};
在任何情况下,使用gapi
的代码在onload
函数(异步)完成之前将无法工作,因此您可能希望将所有相关代码包含在该函数中或进行重组您的代码。