Search code examples
google-chrome-extensionmanifestcontent-security-policyyoutube-iframe-api

How do I allow a chrome extension to access a third-party API script?


I am trying to access a script from YouTube's iframe player API in order to play/pause a video, for a chrome extension. My JS is below (from https://developers.google.com/youtube/iframe_api_reference).

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

function onYouTubePlayerAPIReady() {
    player = new YT.Player('video', {
        events: {
            'onReady': onPlayerReady
        }
    });
}

function onPlayerReady(event) {
    player.playVideo();
}

However, when I load the extension to Chrome, I get the following error:

Refused to load the script 'https://www.youtube.com/iframe_api' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I tried adding the URL to the CSP in Manifest.json (below). I also removed all inline JS.

"content_security_policy": "script-src 'self' https://www.youtube.com/iframe_api; object-src 'self'"

Now, the extension fails to load with an error that my CSP value is invalid. Any idea what I'm doing wrong?


Solution

  • You can check the chrome.scripting.executeScript(), this allows you to load the library and then execute some code that uses it. To do so you need to have it in the same folder as the rest of the extension (just copy the library to a js file). The code that uses the library must be executed after the initial promise of chrome.scripting.executeScript is resolved.

    https://developer.chrome.com/docs/extensions/reference/scripting/#usage