开发者

Can't connect to localhost from Chrome extension

开发者 https://www.devze.com 2023-04-11 05:37 出处:网络
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

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?


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.


You can use custom ports.

manifest.json

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

background.js (using jQuery)

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


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.


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


if you want a generic localhost approach

*://localhost:*/*
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号