使用@include对iframe进行Greasemonkey - 这有用吗?

nop*_*you 9 iframe greasemonkey

我想知道你是否可以只针对iframe执行Greasemonkey执行,而不是它的父窗口.父窗口是域A,iframe是域B,脚本中的include是@include http://domain-B.com/path/*.

我不需要与父母进行任何互动.我已经尝试了几次没有成功.是否存在阻止某人针对iframe执行的跨域限制?

PS:iframe有JS代码阻止它作为顶部窗口加载.

npd*_*oty 11

好吧,当然可以让Greasemonkey针对iframe运行 - 事实上,确定如何阻止它在iframe和主页面上执行是一个常见的问题.你应该能够采取相应的答案,以防止代码在顶部窗口执行:

if (window.top == window.self)  //don't run on the top window
    return;
//rest of the actual executing code goes here
Run Code Online (Sandbox Code Playgroud)

我已经测试了它,您可以使用它@include来匹配域B(域的域iframe)并运行一段修改它的任意代码.我在测试页面上运行了以下测试用户脚本,并成功隐藏了Google徽标(仅当Google位于其中时iframe).

// @include  http://www.google.com*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

if (window.top == window.self)  //don't run on top window
    return;

alert('running on a frame');

$('img').each(function() {
  $(this).hide();
});
Run Code Online (Sandbox Code Playgroud)

据我所知,这里没有任何跨域限制.我不确定如果在iframe首次加载页面时(当Greasemonkey运行时)不存在会发生什么.