3

我正在使用JavaScript,HTML,CSS進行谷歌瀏覽器擴展。爲此,我需要讀取用戶提供的地址的經度和緯度。在測試我的分機,我不斷收到以下錯誤谷歌地圖api不能在谷歌瀏覽器擴展

Error

這裏是我的js代碼

result: { 
      data: function (from, to, hrs, mins) { 
       fromaddress  = from; 
       toaddress = to; 
       hours  = hrs; 
       minutes  = mins; 

       View.result.readLatLng(); 
      }, 

      readLatLng: function() { 
       //var addressone = document.getElementById("addressone").value; 
       geocoder = new google.maps.Geocoder(); 
       geocoder.geocode({ 'address': fromaddress}, function(results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
        var latitude = results[0].geometry.location.latitude; 
        var longitude = results[0].geometry.location.longitude; 
        console.log('lat: ' + latitude + ', lng: ' + longitude); 
        } else { 
        alert("Geocode was not successful for the following reason: " + status); 
        } 
       }); 
      } 
     } 

這裏是我的manifest.json文件

{ 
    "name": "Name", 
    "version": "1.0", 
    "manifest_version": 2, 
    "background": { 
    "scripts": [ 
     "js/result.js", 
     "js/script.js" 
    ] 
    }, 
    "description": "Desc", 
    "browser_action": { 
    "default_icon": "images/icon.png", 
    "default_title": "Title", 
    "default_popup": "html/popup.html" 
    }, 
    "permissions": [ 
    "http://*/", 
    "https://maps.google.com/*", 
    "https://maps.googleapis.com/*", 
    "http://localhost/*", 
    "geolocation" 
    ], 
    "content_security_policy": "script-src 'self' https://maps.googleapis.com https://maps.gstatic.com; object-src 'self'" 
} 

請幫助我如何我能解決這個問題嗎?

+0

你見過這個問題嗎? http://stackoverflow.com/questions/11968234/chrome-extension-uncaught-error-code-generation-from-strings-disallowed-for-th – Marcelo

+0

是的,我讀過一個。我沒有在我的擴展中使用任何模板。所以這沒有幫助。 – 2619

+0

@Marcelo你能幫我一下嗎?預先感謝您 – 2619

回答

0

我在構建Web應用程序時也遇到了Google地理編碼API的問題。您可以立即看到您的代碼存在的潛在問題,這些問題涉及如何獲取經濟緯度和經度。

試試這個:

var latitude = results[0].geometry.location.lat(); 
var longitude = results[0].geometry.location.lng(); 
+0

我爲此有類似的代碼行。 – 2619

+0

當我運行你的代碼時,我得到了「未定義」的緯度和經度。 –

+0

好的。我改變了我的代碼根據你的建議,但我仍然得到相同的錯誤。 – 2619

1

的谷歌地圖API的加載器使用document.write()的,顯然是無法在Chrome擴展允許的。請參閱here

我在Google Chrome的擴展程序中使用您的地圖。現在我嘗試將 切換到Chrome擴展程序manifest.v2,並發現需要使用內容安全策略 。但是你的代碼包含「eval」函數use和 document.write來加載腳本,所以你的地圖不能被初始化。

+0

但我沒有使用文檔。write()方法在我的代碼中的任何地方。 – 2619

+0

你沒有使用它,但Google Maps API是。看看這個來源:http://maps.google.com/maps/api/js?sensor=false – Marcelo

+0

那麼我該如何解決這個問題? – 2619

1

這是答案是編馬塞洛的回答,因爲我還不能發表評論,我的編輯被拒絕。

您可以通過添加'unsafe-eval'屬性改變你的清單文件中"content_security_policy"關鍵規避問題,例如

"content_security_policy": "script-src 'self' 'unsafe-eval' https://; object-src 'self'" 

Discussion of Chrome Extension Content Security Policy

正如在評論中提到對馬塞洛的回答,街景代碼Google Maps API來源使用document.write(),這是一個類似eval的構造。 Eval本質上是不安全的,因此希望Google能夠通過他們的Maps API源代碼解決這個問題。

我不確定這是否會影響向Chrome商店提交擴展程序。但是,我已經成功地將Google Maps API用於本地解壓縮擴展。