我不知道为什么,但我的 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 中尝试过了。
最佳答案
您的目标父页面可能没有实际的
<head>
元素, 导致该脚本实例崩溃。这不是用脚本添加 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,或者您只是有一个愉快的时机意外(目前),但不要依赖您的代码的这种运气。
- 脚本元数据部分/标题对于此类问题至关重要。您的问题需要显示整个脚本。
来自浏览器控制台的错误和指向目标页面的链接也不会出错。
如果脚本适用于 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/