如何从Chrome扩展程序中获取用户的位置?

aamkag61  于 2023-08-01  发布在  Go
关注(0)|答案(2)|浏览(136)

我已经创建了一个扩展,我试图获得用户的位置,这样我就可以向他们显示它。
我尝试添加以下代码:

var x = document.getElementById("ua");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Unavailable.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}

字符串
但延期的时候什么都没有,有什么建议吗?我也尽量避免使用Chrome定位API,因为它只在开发频道上可用。

zlhcx6iw

zlhcx6iw1#

文档中的Declare Permissions页面列出了您案例的特殊权限:
第一个月
允许扩展或应用使用建议的HTML5地理位置API,而无需提示用户获得权限。
您必须使用它,因为某些扩展页面(后台,弹出)无法显示权限信息栏。

mbskvtky

mbskvtky2#

function successCallback(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    const resultDiv = document.getElementById("result");
    resultDiv.textContent = `Latitude: ${latitude}, Longitude: ${longitude}`;
  }
  
  // Function to handle errors when retrieving location
  function errorCallback(error) {
    const resultDiv = document.getElementById("result");
    if (error.code === error.PERMISSION_DENIED) {
      resultDiv.textContent = "Geolocation permission denied. Please allow access in your browser settings.";
      // You can also provide instructions for enabling geolocation in the browser settings.
      const instructionsDiv = document.getElementById("instructions");
      instructionsDiv.textContent = "To enable geolocation access, go to your browser settings, find 'Site Settings' or 'Privacy and Security', and allow location access for this extension.";
    } else {
      resultDiv.textContent = "Error getting location: " + error.message;
    }
  }
  
  // Request user's location when they click the button
  document.getElementById("getLocationButton").addEventListener("click", function() {
    // Check if geolocation is available in the browser
    if ("geolocation" in navigator) {
      // Request the user's location
      navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
    } else {
      const resultDiv = document.getElementById("result");
      resultDiv.textContent = "Geolocation is not available in this browser.";
    }
  });

个字符
并将其包含在您的manifest.json文件中,这是工作。

{
    "name": "name of externsion",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": ["geolocation"],
    "action": {
        "default_popup": "index.html"
    },
    "icons": {
        "16": "images/logo_16.png",
        "24": "images/logo_24.png",
        "32": "images/logo_32.png",
        "64": "images/logo_64.png"
    }
}

相关问题