我正在编写的 chrome 扩展程序中使用内容脚本。我在我的权限列表中包含了 geolocation
,但在每个网页上我仍然会被问到是否要共享我的位置。
我想如果我在权限列表中设置geolocation
,我会避免这种情况吗?这是我的 manifest.json
中的相关代码:
"permissions": ["geolocation"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["main.js"]
}
]
以及我是如何使用它的:
navigator.geolocation.getCurrentPosition(function(position) {
console.log("latitude=" + position.coords.latitude +
", longitude=" + position.coords.longitude);
});
最佳答案
因为您是从内容脚本调用地理定位,所以使用了目标页面的上下文,并且请求看起来像是来自目标页面。所以每个不同的域都必须被授权。 (内容脚本本质上是注入(inject)了具有增强权限的javascript。)
为避免逐个域权限的需要,请从 which is an HTML5 API, not a chrome.* API 调用地理定位 API ( an Event Page ) .
下面是演示该过程的完整扩展:
list .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"
}
main.js:
chrome.runtime.sendMessage ( {command: "gimmeGimme"}, function (response) {
console.log (response.geoLocation);
} );
eventPage.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
}
}
);
关于javascript - 我在 list 中设置了地理定位权限,但每个页面仍然要求共享位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18307051/