【问题标题】:Tampermonkey/Greasemonkey only running in iframesTampermonkey/Greasemonkey 仅在 iframe 中运行
【发布时间】:2014-01-08 01:07:10
【问题描述】:

我不知道为什么,但是我的greasemonkey/tampermonkey 脚本拒绝在具有iframe 的页面上运行。 该脚本在 iframe 内运行,但不在根域上。如果我使用 @noframes 选项,则在带有 iframe 的页面上什么都不会发生。

我什至求助于 // @match http://*/*

我的测试代码很简单……

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';

document.getElementsByTagName('head')[0].appendChild(script)

var title = $('title').html();
alert(title);

这将显示带有 iframe 名称的警报,而不是实际站点。我在greasemonkey 和tampermonkey 中都试过了。

【问题讨论】:

  • 我正在尝试访问父页面,而不是 iframe

标签: javascript iframe greasemonkey tampermonkey


【解决方案1】:
  1. 您的目标父页面可能没有实际的<head> 元素, 导致该脚本实例崩溃。

  2. 这不是您使用脚本添加 jQuery 的方式!您将遇到各种时间问题和代码冲突。
    请参阅this answer for the best cross-platform way to add jQuery 的第二部分(但如果您只使用 GM/TM,那就大材小用了)。还有this bit for resolving jQuery conflicts and crashes in GM/TM scripts。

    可能是 iframe 自己加载了 jQuery,或者你只是有一个快乐的时间意外(现在),但不要依赖这样的运气来编写你的代码。

  3. 脚本元数据部分/标题对于此类问题至关重要。您的问题需要显示整个脚本。
    浏览器控制台的错误和目标页面的链接也不会错。

如果脚本适用于 Tampermonkey/Greasemonkey(不是纯 Chrome),这将起作用:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
var title = $('title').html();
alert(title);

【讨论】:

  • 最初我使用该代码添加 jquery,因为我使用的是 chrome 控制台,而不是 Tampermonkey。不过,感谢您提供有关 @require 标记的信息。效果很好。
猜你喜欢
  • 1970-01-01
  • 2019-01-28
  • 2016-10-03
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2013-11-30
  • 2018-05-15
相关资源
最近更新 更多