Can't connect to localhost from Chrome extension

强颜欢笑 提交于 2019-12-17 23:33:57

问题


I am working on a Chrome extension that tracks time, and uses Google App Engine for the backend.

For testing, I'm trying to connect a local version of the extension to a local version of the App Engine app. When I try to send a POST request, I'm getting:

XMLHttpRequest cannot load http://localhost:8080/report. Origin chrome-extension://mbndmimplohfkkcincjodnfpaapbbmei is not allowed by Access-Control-Allow-Origin.

But it works when I change the URL so that it posts to the appspot.com URL.

What is the Access-Control-Allow-Origin, and why is it stopping me from getting results from localhost?


回答1:


I believe this is because you cannot make calls to a server that is not included in the permissions section of your manifest. The permissions section of manifest.json should look something like this:

"permissions": [
    "http://myapp.appspot.com/*",
    "http://localhost/*"
]

Note, I haven't tested this, but it sounds like that is where your problem is coming from.




回答2:


You can use custom ports.

manifest.json

"permissions": ["http://localhost/*"]

background.js (using jQuery)

$.post('http://localhost:5000/some-endpoint');



回答3:


you cannot add ports within permissions. You have to use port 80 for extensions within permission manifest. I usually run nginx and route all traffic from my extensions to port 80.




回答4:


I was able to get this code to work:

var loginPayload = {};
loginPayload.username = document.getElementById('username').value;
loginPayload.password = document.getElementById('password').value;
console.log(loginPayload);

var callback = function (response) {
    console.log(response);
};
var handle_error = function (obj, error_text_status){
    console.log(error_text_status + " " + obj);
};

$.ajax({
    url: 'https://127.0.0.1:8443/hello',
    type: 'POST',
    success: callback,
    data: JSON.stringify(loginPayload),
    contentType: 'application/json',
    error: handle_error
});

EDIT:
Apparently someone didn't like this, so a few things to keep in mind:

  1. For extensions that have to work on https, make sure your server is serving https.
  2. Contrary to posts above, chrome extensions CAN serve on ports other than port 80 / 443


来源:https://stackoverflow.com/questions/7668502/cant-connect-to-localhost-from-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!