需要在Google Chrome扩展程序中使用外部JavaScript

时间:2016-07-06 07:15:59

标签: javascript google-chrome google-chrome-extension

我想在“内容脚本”Google Chrome扩展程序中使用“YouTube iframe API”。我应该如何在我的扩展程序中使用Youtube iframe API?

Youtube iFrame API的网址:https://www.youtube.com/iframe_api

您通常在清单文件中包含Google Chrome扩展程序中的脚本,但Chrome的扩展程序页面会抛出错误,因为该URL不以.js结尾。

此外,看起来此URL上的脚本会尝试注入<script>标记,这些标记无法与content_script插件一起使用,因为它无法访问该网页的javascript。

的manifest.json

{
    ...
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["main.js"],
            "all_frames": true
        }
    ]
}

main.js

// Inject the script, but this won't work since content scripts can't access the page's javascript (which is where this script is injected).
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";

(document.head || document.documentElement).appendChild(tag);


// Create our own player
var player;

var videoID = 'e7Px2yJA6S4';

// When the YouTube API is loaded, it calls this function.
function onYouTubeIframeAPIReady() {
  player = new YT.Player('movie_player', {
    height: '390',
    width: '640',
    videoId: videoID,
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

我应该做些什么?如何正确包含此脚本?

1 个答案:

答案 0 :(得分:1)

Rob W的回答涵盖了这种情况:Insert code into the page context using a content script,参见方法1&amp;方法2。

通常,因为内容脚本在isolated word中执行,如果您在内容脚本中初始化youtube播放器时将youtube api包含为<script>标记(位于网页世界中)由于内容脚本和<script>标签无法访问彼此定义的变量/函数,因此它将失败。

一种解决方法是通过<script>标记注入这些代码,请参阅以下示例。

的manifest.json

{
    ...
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["inject.js"],
            "all_frames": true
        }
    ],
    "web_accessible_resources": ["https://www.youtube.com/player_api"]
}

inject.js

function insertScriptFile(callback) {
    // Inject the script
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/player_api";
    tag.onload = function () {
        callback();
    };
   (document.head || document.documentElement).appendChild(tag);
}

function insertEmmedCode() {
    var actualCode = `// 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
`;

    var script = document.createElement('script');
    script.textContent = actualCode;
    (document.head || document.documentElement).appendChild(script);
}

var div = document.createElement("div");
div.id = "player";
document.body.appendChild(div);

insertScriptFile(function () {
    insertEmmedCode();
});