我在清单中设置了地理位置权限,但每个页面仍然要求共享位置

Vla*_*ala 2 javascript geolocation google-chrome-extension content-script

我正在使用我正在编写的chrome扩展中的内容脚本.我包含geolocation在我的权限列表中,但在每个网页上,我仍然会被问到是否要分享我的位置.

我想如果我geolocation在权限列表中设置,我会避免这种情况吗?这是我的相关代码manifest.json:

"permissions": ["geolocation"],
"content_scripts": [
 {
   "matches": ["<all_urls>"],
   "js": ["main.js"]
 }
]
Run Code Online (Sandbox Code Playgroud)

以及我如何使用它:

navigator.geolocation.getCurrentPosition(function(position) {
    console.log("latitude=" + position.coords.latitude +
    ", longitude=" + position.coords.longitude);
});
Run Code Online (Sandbox Code Playgroud)

Bro*_*ams 6

因为您从内容脚本调用地理位置,所以使用目标页面的上下文,并且请求看起来像是来自目标页面.因此,必须授权每个不同的域.(内容脚本基本上是以增强的权限注入javascript.)

为避免需要逐域权限,请从事件页面调用地理位置API(HTML5 API,而不是chrome.*API).

这是一个完整的扩展,演示了这个过程:

manifest.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"
}
Run Code Online (Sandbox Code Playgroud)


main.js:

chrome.runtime.sendMessage ( {command: "gimmeGimme"}, function (response) {
    console.log (response.geoLocation);
} );
Run Code Online (Sandbox Code Playgroud)


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
        }
    }
);
Run Code Online (Sandbox Code Playgroud)