javascript - Tampermonkey/Greasemonkey 仅在 iframe 中运行

标签 javascript iframe greasemonkey tampermonkey

我不知道为什么,但我的 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 中尝试过了。

最佳答案

  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);

关于javascript - Tampermonkey/Greasemonkey 仅在 iframe 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20682122/

相关文章:

javascript - jQuery + SVG : unable to access SVG element in iFrame

javascript - html - 从文本区域获取换行文本

javascript - 为什么 waitForKeyElements() 尽管后来发生了变化,但只触发一次?

javascript - 某些东西导致这个 CSS 崩溃

javascript - 更改索环组件的 colorIndex

javascript - RHS 分配优于 LHS 操作

javascript - iframe 子级与多个 iframe 的父级通信

javascript - 如何使用 Greasemonkey 选择没有标识符的 div?

javascript - Greasemonkey/Tampermonkey 自动点击隐藏值和提交值?

javascript - 获取 json 数据时 jquery 有问题