【问题标题】:Javascript with Grease Monkey : @grant messes up Youtube API带有 Grease Monkey 的 Javascript:@grant 搞乱了 Youtube API
【发布时间】:2015-10-10 09:49:26
【问题描述】:

我正在使用 GM 为网站编写自定义脚本。该脚本在页面中添加了一个嵌入的 Youtube 播放器,所以我调用了 Youtube API。这是代码的开头:

// ==UserScript==
// @author       mens
// @match        http://thewebsite.com
// @grant        none
// ==/UserScript==

///////////// YOUTUBE

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

// API loaded
window.onYouTubeIframeAPIReady = function()
{
    console.log("API loaded");
}

使用此代码,一切正常。前几行调用 API,加载后触发 onYouTubeIframeAPIReady,然后在我的脚本中生成 player。

您会注意到@grant 设置为none。问题是当我改变这条线时,即使是最轻微的。我使用GM_getResourceURL 访问外部文件(如图形)。

所以当我设置时:

// @grant        GM_getResourceURL

...API 不再工作:onYouTubeIframeAPIReady 永远不会被调用!

根据我在 GM 文档中收集的信息,@grant none 是默认模式,这意味着对代码中使用的所有 API 的最大访问权限。更改 @grant 时可能会出现更多限制...我认为这是问题的一部分,但我不知道如何处理它。

感谢您的帮助!!

【问题讨论】:

  • 您是否考虑过使用@require 来代替插入script 标签?
  • 是的,我试过了,然后我得到一个错误:Uncaught TypeError: YT.Player is not a function... 用于创建播放器的 YT 对象似乎没有完全加载
  • 问题谁的答案将解决这个问题stackoverflow.com/questions/13485122/…(但技术上不是重复的)

标签: javascript youtube


【解决方案1】:

所以诀窍很简单(但很神秘):我通过重命名函数将window 更改为unsafeWindow:

unsafeWindow.onYouTubeIframeAPIReady = function()
{
    console.log("API loaded");
}

来自 GM 文档:

不安全的窗口

unsafeWindow 对象提供对页面 javascript 函数和变量的完全访问。

似乎除none 之外的任何@grant 都将window 对象放入沙箱中,外部API 访问受限。我仍然不确定如何正确设置这些限制,但unsafeWindow 完全绕过它们。

【讨论】:

【解决方案2】:

不是这个

// API loaded
window.onYouTubeIframeAPIReady = function()
{
    console.log("API loaded");
}

这样做

function apiReady() {
    console.log("API loaded");
}
exportFunction(apiReady, unsafeWindow, {defineAs: "onYouTubeIframeAPIReady"});

exportFunction的解释见Mozilla docs

但是,我自己还不是 100% 相信这比直接使用 unsafeWindow 更“安全”(在greasemonkey 中)

根据我在 GM 文档中收集的信息,@grant none 是默认模式,这意味着对代码中使用的所有 API 的最大访问权限。

这是不正确的。 @grant none 所做的是明确关闭 ALL 油脂猴 API(GM* 函数)并在没有沙箱的情况下运行脚本,因为流氓网站不可能使用油脂猴反对你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多