因为您是从内容脚本调用地理位置,所以使用了目标页面的上下文,并且请求看起来像是来自目标页面。所以每个不同的域都必须被授权。(内容脚本本质上是注入了增强权限的 javascript。)
为避免逐个域权限的需要,请从Event Page调用 geolocation API(它是一个 HTML5 API,而不是 chrome.* API)。
这是演示该过程的完整扩展:
清单.json:
{
"manifest_version": 2,
"permissions": ["geolocation"],
"content_scripts": [ {
"js": [ "main.js" ],
"matches": [ "<all_urls>" ]
} ],
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"name": "_Read browser location",
"description": "See SO Q 18307051. Scarf location without spamming warnings",
"version": "1"
}
主.js:
chrome.runtime.sendMessage ( {command: "gimmeGimme"}, function (response) {
console.log (response.geoLocation);
} );
事件页面.js:
chrome.runtime.onMessage.addListener (
function (request, sender, sendResponse) {
if (request.command == "gimmeGimme") {
navigator.geolocation.getCurrentPosition (function (position) {
sendResponse ( {
geoLocation: (
"latitude=" + position.coords.latitude
+ ", longitude=" + position.coords.longitude
)
} );
} );
return true; // Needed because the response is asynchronous
}
}
);