Как я могу использовать Google API в расширении Chrome? - PullRequest
0 голосов
/ 01 мая 2019

Я часами ищу, как можно использовать Google API в расширении Chrome. Все, что я хочу сделать, - это проанализировать содержимое веб-сайта и вставить его как новое событие в Google Calender. Я получил разбор и все, но, кажется, невозможно использовать Google API внутри расширения Chrome. Я просто пытаюсь написать пример события при нажатии кнопки в моем расширении Chrome, но он продолжает отказываться загружать Google API с этой ошибкой:

Refused to load the script 'https://apis.google.com/js/platform.js' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Мой манифест.json:

{
    "manifest_version": 2,

    "name": "DVB2Calender",
    "description": "This extension will export the current viewed schedule to your Google Calender.",
    "version": "1.0",

    "content_security_policy": "script-src 'self' https://apis.google.com/; object-src 'self'",

    "browser_action": {
     "default_icon": "icon.png",
     "default_popup": "popup.html"
    },
    "permissions": [
     "activeTab"
     ]
}

Мой popup.html

<!doctype html>
<html>
  <head>
    <title>DVB2Calender</title>
    <meta http-equiv="Content-Security-Policy" content="default-src *;">
    <script src="popup.js"></script>
    <script src="https://apis.google.com/js/platform.js" async defer>
    </script>
  </head>
  <body>

    <h1>DVB to Calender</h1>
    <button id="exportToCalender">Export this calender to Google Calender!</button>

  </body>
</html>

My popup.js:

document.addEventListener('DOMContentLoaded', function() {
    var checkPageButton = document.getElementById('exportToCalender');
    checkPageButton.addEventListener('click', function() {

        chrome.tabs.getSelected(null, function(tab) {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = "https://apis.google.com/js/client.js?onload=callbackFunction";
            head.appendChild(script);

            d = document;
            var download = d.getElementsByClassName('icon-link ico-calender')[6];
            var request = makeHttpObject();
            request.open("GET", download, true);
            request.send(null);
            request.onreadystatechange = function() {
                if (request.readyState === 4) {
                    var resultText = request.responseText;
                    array = CSVToArray(resultText, ":");
                    alert(resultText);

                    var resource = {
                        "summary": "Appointment",
                        "location": "Somewhere",
                        "start": {
                        "dateTime": "2011-12-16T10:00:00.000-07:00"
                        },
                        "end": {
                        "dateTime": "2011-12-16T10:25:00.000-07:00"
                        }
                    };
                    var request = gapi.client.calendar.events.insert({
                    'calendarId': 'primary',
                    'resource': resource
                    });
                    request.execute(function(resp) {
                    console.log(resp);
                    });
                }
            };
        }
    }
}

1 Ответ

1 голос
/ 02 мая 2019

Похоже, вы просто забыли перезагрузить пакет расширения.Обратите внимание, что каждый раз, когда вносятся изменения в код расширения, необходимо выполнить перезагрузку, которую можно выполнить здесь chrome://extensions/, чтобы изменения кода вступили в силу.

chrome extension package reload

Чтобы проверить, готов ли клиентский сценарий к использованию, предлагается добавить обратный вызов onload следующим образом:

window.callbackFunction = function(){
  alert('client.js ready')
  // here goes google client api calls
}

Имя функции обратного вызова onload задается параметром onload в URL-адресе сценария.

...