我正在将请求从内容脚本切换到后台脚本,代码是相同的,但不知何故,XMLHttpRequest不会让我登录。
我的目标是登录用户并更改密码 - 这需要2个POST请求。第二个失败了。
老实说,我不知道该做什么,完全迷失了。
背景脚本:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
// FIRST REQUEST
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", "https://.../login.php", true);
loginRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
loginRequest.send("user credentials...");
loginRequest.onload = function() {
// SECOND REQUEST
var changeRequest = new XMLHttpRequest();
changeRequest.open("POST", "https://.../changePassword", true);
changeRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
changeRequest.send("old pass... new pass...");
changeRequest.onload = function() {
// ISSUE: changeRequest.responseURL is back at the login page? WHY?
if (changeRequest.responseText.includes("Password successfully changed!")) {
sendResponse({passwordChanged: true});
} else {
sendResponse({passwordChanged: false});
}
}
}
return true;
});
请注意:此代码在内容脚本中完美运行!
loginRequest.anonymous = true;
从后台脚本发送时,由于不必要的cookie而解决了问题。