Possibile使用Manifest v2下的HTML5地理位置API将lat/long转换为国家/地区

Possibile to convert lat/long to country using HTML5 geolocation API under Manifest v2?

本文关键字:long lat 转换 地区 国家 API Manifest 使用 v2 下的 地理位置      更新时间:2023-09-26

我有一个在Manifest v2下运行的Google Chrome扩展。之前,我可以与http://www.geoplugin.net/javascript.gp并且被提供有用户国家代码(例如美国、英国)。然而,Manifest v2施加了限制,禁止与非https、白名单网站对话。这意味着我不能再去服务器上获取信息了。

我想继续拥有这个功能。我相信我的最佳选择是利用HTML5地理位置将坐标转换为国家代码。我还没有看到这方面的任何实现。这有可能在合理的范围内实现吗?我在网上找到的所有解决方案都建议与服务器通信,但我没有遇到https解决方案。

我还考虑过尝试与"https://maps.googleapis.com/maps/api/geocode/",但是,即使将其添加到content_security_policy中,我也无法查询JSON。

只是好奇是否有人有我没有看到的解决方案/已经解决了这个问题

我在jQuery中使用了RobW的答案:

$.get('http://www.geoplugin.net/json.gp', function(result){
    var geoplugin = JSON.parse(result.replace(/^[^'{]+/, '').replace(/');?$/, ''));
    console.log(geoplugin.geoplugin_countryCode);
});

在Chrome扩展中,当URL在清单文件的"permissions"部分被列入白名单时,您可以进行跨源请求。

的输出http://www.geoplugin.net/json.gp(注:json而非javascript):

geoPlugin({
  "geoplugin_request":"x.x.x.x",
  "geoplugin_status":200,
  "geoplugin_city":"...",
  ...
})

此输出格式不是JSON,而是JSONP。函数调用不相关。所以在解析之前去掉填充(geoPlugin()):

var xhr = new XMLHttpRequest();
xhr.onload = function() {
    var json = xhr.responseText.replace(/^[^'{]+/, '').replace(/');?$/, '');
    json = JSON.parse(json);
    // Example, alert latitude and longitude
    alert(json.geoplugin_latitude + ', ' + json.geoplugin_longitude);
};
xhr.open('GET', 'http://www.geoplugin.net/json.gp');
xhr.send();

清单文件:

  ...
  "permissions": ["http://www.geoplugin.net/json.gp"],
  ...