所以我正在創建Google Chrome擴展程序,起初我是通過內容腳本注入我的html,angular和javascripts。不,我需要自己注射。我做到了!但問題是,當它通過內容腳本注入我的登錄方法工作得很好,作爲回報我得到了令牌(這就是我所需要的),但是當我自己注入登錄函數不再工作時,它會拋出此錯誤:
angular.module('app').controller('LoginController', LoginController);
LoginController.$inject = ['$scope', '$http', '$location', '$state'];
function LoginController($scope, $http, $location, $state) {
$scope.login = function (user) {
user.grant_type = 'password';
return $http({
method: 'POST',
url: 'http://www.cheapwatcher.com/api/Authenticate',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Access-Control-Allow-Origin': '*'
},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: user
}).success(function (result) {
console.log(result);
$(".cheap-watcher").fadeOut(1500, function() {
$(".cheap-watcher").fadeIn($state.go("logout"), {}, { location: false }).delay(2000);
})
}).error(function (result) {
console.log(result);
});
};
};
我可以不用在服務器端進行CORS東西:
XMLHttpRequest cannot load http://www.cheapwatcher.com/api/Authenticate . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://anywebsitename.com ' is therefore not allowed access. The response had HTTP status code 400.
這是我的登錄方法(我沒有因爲改變了噴射式改變任何東西)?因爲正如我所說的通過內容腳本注入工作就好了
更新!
所以我將我的登錄方法從$ http更改爲$ .ajax。一切都是一樣的,而不是$ http我寫了$ .ajax並刪除了標題部分。在鉻源控制中,錯誤是一樣的,但現在在提琴手中,我可以看到我的請求成功了。這怎麼可能?
現在登錄方法如下:
angular.module('app').controller('LoginController', LoginController);
LoginController.$inject = ['$scope', '$http', '$location', '$state'];
function LoginController($scope, $http, $location, $state) {
$scope.login = function (user) {
user.grant_type = 'password';
return $.ajax({
url: "http://www.cheapwatcher.com/api/Authenticate",
crossDomain: true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
method: 'POST',
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: user
}).success(function (result) {
console.log(result);
$(".cheap-watcher").fadeOut(1500, function() {
$(".cheap-watcher").fadeIn($state.go("logout"), {}, { location: false }).delay(2000);
})
}).error(function (result) {
console.log(result);
});
};
};
UPDATE NR。 2!
我看到錯誤來自http://anywebsitename.com的索引頁。所以我假設我的登錄請求不是從我的擴展中運行,而是從網站內容中運行。是否有任何可以從注入腳本到後臺腳本的通信?
將是很好,如果這是這麼簡單...我的權限部分包含**「http:// */*」**和**「https:// */*」**,所以它應該可以工作。 - @haibaraAi –
@NikasŽalias,你最好把你的ajax調用放在後臺腳本中,如果你聲明瞭權限,那麼這個腳本不會被同源策略阻塞。您可以查看官方指南[消息傳遞](https://developer.chrome.com/extensions/messaging)以瞭解有關內容腳本與後臺頁面之間通信的詳細信息。 –