XMLHttpRequest in Chrome Extension with HTTP Authorization continues to send Authorization Header on regular pages
I am working on a chrome extension that works with the Basecamp API.
I have a background page doing all my XMLHttpRequests to the API. I'm not using OAuth, but the basic HTTP Authorization with the API Token.
In my background page, I will do requests like this:
var xmlReq = new XMLHttpRequest();
xmlReq.onreadystatechange = function(){ doSomething(xmlReq.responseXML); };
xmlReq.open(
'GET',
'https://mycompany.basecamphq.com/projects.xml',
true,
access_token,
'x'
);
xmlReq.s开发者_开发技巧end(null);
That all works fine, but the problem is after I use the extension to make a request, the HTTP Request header Authorization is being sent whenever I browse to https://mycompany.basecamphq.com, which make certain things not work on Basecamp's web interface. How can I make a request in my extension with basic HTTP Authorization but not have the header in my regular browser requests?
Yeah, confusing question. I'll try to clarify it if you have questions. Thanks
I believe I have figured out a solution.
By using the xmlhttpresponse.setRequestHeader() function, if I manually set the authorization header, it doesnt stay persistent.
So using this modified version of the above code:
xmlReq.open(
'GET',
'https://mycompany.basecamphq.com/projects.xml',
true);
xmlReq.setRequestHeader("Authorization", "Basic "+base64_encode(access_token+":x"));
xmlReq.send(null);
I used the base64_encode function found in the phpjs.org library.
I'm just adding on this this for those using Google Apps Script. You can get the same behavior there by doing this:
function myFunc(){
var parameters = {
method: "GET",
accept: "application/xml",
contentType: "application/xml",
headers: {"Authorization": "Basic " +Utilities.base64Encode("YOUR_BASECAMP_ACCESS_TOKEN:GARBAGE_PASSWORD")}
};
var baseURL = "https://YOUR_COMPANY_NAME.basecamphq.com/projects.xml";
var text = UrlFetchApp.fetch(baseURL, parameters);
Logger.log(text.getContentText());
}
You can run that, then hit View > Logs to see the results. More info here: http://developer.37signals.com/basecamp/index.shtml but it's written assuming you know your way around requests.
精彩评论