Как сделать политику безопасности контента Google Api для Google Maps - PullRequest
1 голос
/ 21 апреля 2020

Я пытаюсь использовать Electron. js для создания небольшого приложения и пытаюсь добавить на него страницу карт Google. Я уже получил ключ API. Когда я запускаю приложение, оно на короткое время показывает изображение Карт Google, а затем появляется сообщение об ошибке: «Ой! Что-то пошло не так. Эта страница неправильно загрузила Карты Google. Технические сведения см. В консоли JavaScript». Когда я открываю консоль, я вижу ошибку:

"security-warnings.ts:179 Electron Security Warning (Insecure Content-Security-Policy) This renderer process has either no Content Security
    Policy set or a policy with "unsafe-eval" enabled. This exposes users of
    this app to unnecessary security risks.

For more information and help, consult
https://electronjs.org/docs/tutorial/security.
This warning will not show up
once the app is packaged.
(anonymous) @ security-warnings.ts:179
Promise.then (async)
warnAboutInsecureCSP @ security-warnings.ts:172
logSecurityWarnings @ security-warnings.ts:295
loadHandler @ security-warnings.ts:312
async function (async)
loadHandler @ security-warnings.ts:311
load (async)
securityWarnings @ security-warnings.ts:315
(anonymous) @ init.ts:216
./lib/renderer/init.ts @ init.ts:217
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83
NativeModule.compile @ internal/bootstrap/loaders.js:287
NativeModule.compileForPublicLoader @ internal/bootstrap/loaders.js:222
loadNativeModule @ internal/modules/cjs/helpers.js:23
Module._load @ internal/modules/cjs/loader.js:699
Module._load @ electron/js2c/asar.js:717
Module._load @ electron/js2c/asar.js:717
Module.runMain @ internal/modules/cjs/loader.js:1038
(anonymous) @ internal/main/run_main_module.js:17
js?key=MY_API_KEY&callback=initMap:56 Google Maps JavaScript API error: ApiNotActivatedMapError
https://developers.google.com/maps/documentation/javascript/error-messages#api-not-activated-map-error
_.od @ js?key=MY_API_KEY&callback=initMap:56
(anonymous) @ common.js:73
(anonymous) @ common.js:149
c @ common.js:67
(anonymous) @ AuthenticationService.Authenticate?1sfile%3A%2F%2F%2FUsers%2Fisaiahbell%2FProjects%2Fgeo-app%2Fmap.html&MY_API_KEY&callback=_xdc_._m2aezz&key=YOUR_API_KEY&token=54562:1"

Мой текущий код выглядит следующим образом:

Индекс. html

 <!DOCTYPE html>
    <html>
      <head>
        </head>
      <body>


        <center>
          <a href="map.html">Open Maps</a>
        </center>








         <script src="./render.js"></script>
      </body>
    </html>




    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    type="text/javascript"></script>

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">


        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
      </head>
      <body>

map. html:

<!DOCTYPE html>

<html>

  <head>



    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple Markers</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>



  </head>
  <body>
    <button><a href="index.html">Go Back</a><</button>
    <div id="map"></div>
    <script>

      function initMap() {
        var myLatLng = {lat: -25.363, lng: 131.044};

        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: myLatLng
        });

        var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          title: 'Hello World!'
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
    </script>
  </body>
</html>

1 Ответ

0 голосов
/ 23 апреля 2020

Обратите внимание, что вы получаете эту ошибку:

Карты Google JavaScript Ошибка API: ApiNotActivationMapError https://developers.google.com/maps/documentation/javascript/error-messages#api -не-активируемая-карта-ошибка

Это означает, что вам нужно включить API JavaScript в вашем проекте.

Если этот параметр включен, у вас возникают ошибки, связанные с CSP, которые мешают загрузке вашей карты , затем посмотрите Как разрешить внешнюю javascript политику безопасности контента из Google API?

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...