代码之家  ›  专栏  ›  技术社区  ›  Nathan Wheeler

javascript iframe总线

  •  2
  • Nathan Wheeler  · 技术社区  · 15 年前

    在某些情况下,我有一个在iframe中打开的网页。当它加载到该iframe中时,我需要它将窗口位置设置为资源以下载文件(所有这些都是为了更新greasemonkey脚本…全部合法,顺便说一句)。不幸的是,当我这样做的时候:

    top.location.href = "http://userscripts.org/...";
    

    我收到一个错误,说明top为空。当使用“window”代替“top”时,firefox将我的脚本文本加载到iframe中,但是greasemonkey由于某种原因无法检测到它作为更新。有没有其他方法可以设置我错过的窗口位置?

    编辑:我的脚本的用户访问特定业务的页面(首先)。我的脚本使用一个名为greasemonkey的火狐插件加载到该页面。我的脚本在访问过的页面上创建一个iframe,并将我的页面(第二个)加载到该iframe中。然后,GreaseMonkey将我的脚本加载到我的页面上,该页面检查我页面上的值,以查看脚本是否已更新。如果脚本已经更新,我需要将我的用户从他们最初访问的站点(记为“第一个”)导航到另一个(第三个)站点(userscripts.org)。希望这能消除一些混乱。

    5 回复  |  直到 14 年前
        1
  •  3
  •   Nathan Wheeler    15 年前

    我最终发现GreaseMonkey提供了一个“gm_OpenIntab(url)”函数,它在firefox中用指定的url打开了一个新的标签。这允许我的iframe打开一个新选项卡,其中包含更新脚本的位置,以便greasemonkey进行更新。虽然这不是我一直在寻找的解决方案,但它可以无缝地工作,没有任何错误。

    GM_openInTab("http://userscripts.org/...") ;
    

    感谢大家的意见。有可能,GreaseMonkey以某种方式沙盒脚本来防止这种可能用于恶意目的的行为。

    ~Md5SUM~

        2
  •  1
  •   Josh Stodola    15 年前

    两个位置必须具有相同的主机名(域)。你可能想用 parent 而不是 top .

        3
  •  1
  •   Pool    15 年前

    您可以尝试以下方法(根据我使用的内容改编):

    function checkWebPage() {
        try {
            if (top != self) {
                top.location.href = "http://userscripts.org/...";
            } else {
                self.location.href = "http://userscripts.org/...";
            }
        } catch (e) {}
    }
    
        4
  •  0
  •   andres descalzo    15 年前

    我在iframe上工作过几次,发现使用文档状态更安全。我将通过一个示例传递一个代码。

    在本例中,我使用的是jquery,但对于功能来说,它不是必需的。

    <head>
    <script>
    (function($) {
     $.documentCtrolState = function(d,f,t)
     {
        try{
          t=(typeof(t)=="undefined")?100:t;
          if (d.readyState=="complete") //the document has been completely loaded, successfully or unsuccessfully
             f(true);
          else
             setTimeout(function(){$.documentCtrolState.call(this,d,f,t);}, t);
        }catch(ex){
             f(false, ex);
        }
     };
    })(jQuery);
    
    $(function(){
    
       $myIframeRef = $(document.myIFrame);
       $myIframeRef.attr("src", "mypage.php");
    
       $.documentCtrolState($myIframeRef.window.document, ThenLoadIFrame, 100);
    
    });
    
    ThenLoadIFrame = function(state, ex)
    {
       alert("State " + state);
    }
    
    
    </script>
    </head>
    <body>
    <iframe src="" id="myIFrame"></iframe>
    </body>
    
        5
  •  0
  •   Steven    14 年前

    unsafewindow.parent.location.href=url;在Greasemonkey为我工作。