我正在开发Chrome扩展程序,我遇到了一个问题:
“未捕获的ReferenceError:未定义gapi”。
我正在向gapi发送XML请求。它被加载,但在使用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'"
}
虽然您使用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
的代码都不会有效,因此您可能希望在该函数中包含所有相关代码或重新构造代码。