jQuery在iframe的top / main窗口中隐藏/访问元素

时间:2018-02-07 18:44:39

标签: javascript jquery iframe window parent

我正在使用CRM系统,我无法控制系统生成的HTML。这是我正在处理的最简单的HTML标记形式。

<button id="cmdedit">Edit</button>
<textarea cols="30" rows="10"> Hi there </textarea>
<iframe src="s_blank.html" frameborder="0"></iframe>

我想在页面加载后隐藏cmdedit <button>。我只能更改<textarea>的内容,然后在页面加载时将其作为以下<iframe>的HTML内容插入到DOM中。我可以包含<script>标记并编写进入<iframe>的javascript或Jquery语句,并且javascript警告语句可以正常工作。我尝试使用以下代码隐藏<button>,但在页面加载后都不起作用。

iframe中的脚本:

<script type="text/javascript">
     $(document).ready(function(){         
        var MyRoleList = "@me.rolelist@";
        if (MyRoleList.indexOf(",9875,") > -1){         
            alert('aaa');   
            $('#cmdedit').hide();     
        }
     });
  </script>

系统生成的完整HTML

<html lang="en"><head>
    <title>Examinee Notice</title>
    <link rel="icon" type="image/x-icon" href="/images/favicon.ico">
	<link rel="SHORTCUT ICON" href="/images/favicon.ico">
	<link rel="stylesheet" type="text/css" href="/css/ccss/styles_common_basic_404048.css?version=201711.05">

    <link rel="stylesheet" type="text/css" media="screen" href="/jquery/jquery-confirm-master/css/jquery-confirm.css?v=201711.05">
    <script language="JavaScript" src="/jquery/jquery.js?v=201711.05"></script><style></style>
    <script type="text/javascript" src="/jquery/jquery-confirm-master/dist/jquery-confirm.min.js?v=201711.05"></script>
    <script type="text/javascript" language="JavaScript" src="/Ajax/uta/uta.js?v=201711.05"></script>
    <script type="text/javascript" language="JavaScript" src="/js/ssvalidate.js?v=201711.05"></script>
    <script type="text/javascript" src="/js/ssfieldfunctions.js?v=201711.05"></script>
    <script type="text/javascript" src="/js/ssfunctions.js?v=201711.05"></script>
    <script language="javascript">
        var _iseditmode=false;
            function jqueryalert(msg, confirmfn) {
                $.confirm({
                    title: "Hey Muhammad",
                    content: msg,
                    icon: 'fa fa-exclamation-triangle',
                    theme: 'material',
                    animation: 'scale',
                    closeAnimation: 'scale',
                    type: 'orange',
                    buttons: {
                        confirm: {
                            text: "OK",
                            btnClass: 'btn-orange',
                            keys: ['enter'],
                            action: function() {
                                if (confirmfn) {
                                    confirmfn();
                                }
                            }
                        }
                    }
                });
            }
            function jqueryconfirm(msg, confirmfn, cancelfn) {
                $.confirm({
                    title: "Hey Muhammad",
                    content: msg,
                    icon: 'fa fa-exclamation-triangle',
                    theme: 'material',
                    animation: 'scale',
                    closeAnimation: 'scale',
                    type: 'orange',
                    buttons: {
                        confirm: {
                            text: "Yes",
                            btnClass: 'btn-orange',
                            action: function() {
                                if (confirmfn) {
                                    confirmfn();
                                }
                            }
                        },
                        cancel: {
                            text: "No",
                            action: function() {
                                if (cancelfn) {
                                    cancelfn();
                                }
                            }
                        }
                    }
                });
            }
            function jqueryprompt(msg, confirmfn, cancelfn) {
                $.confirm({
                    title: "Hey Muhammad",
                    content: msg,
                    icon: 'fa fa-exclamation-triangle',
                    theme: 'material',
                    animation: 'scale',
                    closeAnimation: 'scale',
                    type: 'orange',
                    buttons: {
                        confirm: {
                            text: "Continue",
                            btnClass: 'btn-orange',
                            keys: ['enter'],
                            action: function() {
                                if (confirmfn) {
                                    if (!confirmfn(this.$content)) {
                                        return false;
                                    }
                                }
                            }
                        },
                        cancel: {
                            text: "Cancel",
                            keys: ['esc'],
                            action: function() {
                                if (cancelfn) {
                                    cancelfn();
                                }
                            }
                        }
                    }
                });
            }
        function no_error()
        { return true; }
        //window.onerror=no_error;

        function getsrc()
        { var frm=window.frames["page_win"].document.forms[0];
            if(frm==null) return "";
            var valuestr='\n var frm_inp=document.forms[0];\n';
            var ctltype;
            for (var i=0;i<frm.elements.length;i++)
            { ctltype=frm.elements[i].type.toLowerCase();
                if(ctltype=='radio'||ctltype=='checkbox')
                { if (frm.elements[i].checked)
                        valuestr+='\nfrm_inp.elements['+i+'].checked=true;';
                }
                else
                    valuestr+='\nfrm_inp.elements['+i+'].value=decodeURIComponent("'+encodeURIComponent(frm.elements[i].value)+'");';
            }

            return valuestr;
        }



        function puttxt()
        {
            window.frames["page_win"].document.writeln(document.frmtext.txt.value);
            window.frames["page_win"].document.close();
            var cmd=document.getElementById('cmdprint');
            if(cmd!=null)
                cmd.style.display="inline";
            cmd=document.getElementById('cmdemail');
            if(cmd!=null)
                cmd.style.display="inline";
            cmd=document.getElementById('cmdpdf');
            if(cmd!=null)
                cmd.style.display="inline";
            
            cmd=document.getElementById('cmddocx');
            if(cmd!=null)
                cmd.style.display="inline";
            
            cmd=document.getElementById('cmdemailpdf');
            if(cmd!=null)
                cmd.style.display="inline";
            cmd=document.getElementById('cmdemaildoc');
            if(cmd!=null)
                cmd.style.display="inline";
            if (window.frames["page_win"]!=null && window.frames["page_win"].ss_load)
                window.frames["page_win"].ss_load();
            if(window.frames["page_win"]!=null)window.frames["page_win"].focus();
        }

        function editdoc(button)
        {
            if(!_iseditmode)
            {window.frames["page_win"].location.href='/s_editor.html';
                button.value="Preview";



                _iseditmode=true;
            }else
            {  document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();

                window.frames["page_win"].document.writeln(document.frmtext.txt.value);
                window.frames["page_win"].document.close();
                button.value="Edit";
                _iseditmode=false;
            }

            switchbut(button.form,'cmdprint');
            switchbut(button.form,'cmdnewin');
            switchbut(button.form,'cmdemail');
            switchbut(button.form,'cmdemailpdf');
            switchbut(button.form,'cmdemaildoc');
            switchbut(button.form,'cmdpdf');
            switchbut(button.form,'cmdsavehtml');
            switchbut(button.form,'cmdsavepdf');
            switchbut(button.form,'cmdsavedoc');
            if ($('#functable').css("display") == "none")
                $('#functable').css("display", "table");
            else
                $('#functable').css("display", "none");
        }

        function switchbut(frm ,ctl)
        { var octl =frm.elements[ctl];
            if (octl!=null)
            {
                octl.disabled=!octl.disabled;
                if (octl.disabled)
                    $('[name="'+ctl+'"]').css("display", "none");
                else
                    $('[name="'+ctl+'"]').css("display", "inline");
            }
        }
        function CheckIsIE()
        {
            return (navigator.appName.toUpperCase().indexOf('MICROSOFT')>-1) ;

        }


        function printdoc()
        {

            if (CheckIsIE() == true)
            {
                document.page_win.focus();
                document.page_win.print();
            }
            else
            {
                window.frames['page_win'].focus();
                window.frames['page_win'].print();
            }

        }

        function savelocal(fname)
        {
            window.frames["page_win"].document.execCommand('SaveAs',null,fname)
        }


        function saveserver(type)
        { 
            if(_iseditmode) {
                document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
            }
            var frm=document.frmtext;
            frm.filename.value=frm.filename.value.replace(/\.html/,"");
            frm.filename.value=frm.filename.value.replace(/\.pdf/,"");

            if(frm.mfolderid.value=='') {
                alert("Please select a folder name to save to.");
                return false;
            }
            
            var html = "<div class=\"form-group\" style=\"text-align:center\"><div style=\"margin:5px\">Please enter a file name.</div><input class=\"Large\" type=\"text\" placeholder=\"File Name\" class=\"form-control\" id=\"filenameprompt\" value=\"" + frm.filename.value + "\"/></div>";
            jqueryprompt(html, function(promptobj) {
                var frm = document.frmtext;
                var newf = promptobj.find("#filenameprompt").val();
                if (newf == '') {
                    alert("File name cannot be empty.");
                    return false;
                } else if (!isValidFileName(newf)) {
                    alert("File name contains invalid characters (;,#,=,?)");
                    return false;
                }
                frm.filename.value=newf.replace(/\s|\/|\\/g,'_');
                saveserversb(type)
                return true;
            });
            
        }
        function saveserversb(type) {
            
            saveserversb2(type);
            
        }
        function saveserversb2(type) {
            var frm=document.frmtext;
            var id=frm.mfolderid.value;
            if (id.indexOf('-')>0) {
                frm.objectid.value=id.substring(0,id.indexOf('-'));
                frm.folderid.value=id.substring(id.indexOf('-')+1);
            } else {
                frm.folderid.value=frm.mfolderid.value;
            }
            frm.action='s_savetextfile.jsp?type='+type;
            frm.target='page_win';
            frm.submit();
        }
    function newwind(frm)
    { var src;
        if(_iseditmode)
            src=window.frames["page_win"].oCKeditor.getData();
        else
            src=frm.txt.value;

        OpenWindow=window.open("", "newwin", "menubar=yes,scrollbars=yes,width=550,height=300,status=no,resizable=yes,dependent=yes,alwaysRaised=yes");
        OpenWindow.document.write(src);
        OpenWindow.document.close()
    }

    function newwinda()
    {
        var frm = document.frmtext;
        var inf = frm.txt.value;
        win = window.open("", "newwina", "menubar=yes,scrollbars=yes,width=650,height=500,status=no,resizable=yes,dependent=yes,alwaysRaised=no");
        win.document.write("" + inf + "");
        win.document.close();
    }

    function gotohcai()
    {   alert('When submitting to HCAI, please be aware that the submission time frame can vary between 0-120 min. If your submission is surpassing this time frame, please notify SmartSimple Support.', function() {
            location.href="/Apps/Bridge/hc_submissions.jsp?fieldid=1274403&entity=24&objectid=1127956&appid=102946";
        });
    }
    function gotosignority() {
        showsave("Load in Progress");
        location.href="/Apps/Bridge/sg_signority.jsp?fieldid=1274403&entity=24&objectid=1127956&appid=102946&codedid=QHJrJ0keIhgKFlALJGc1KgRXEAcuXRsTH2JcU0VNZl8~&islb=0&exportpdf=0&ismwin=0";
    }



        function emailpdf() {
            if(_iseditmode)
                document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();

            var frm=document.frmtext;
            frm.body.value=frm.txt.value;

            
            emailpdfsb();
            
        }
        function emailpdfsb() {
            var frm=document.frmtext;
            window.open("", "comp_win", "menubar=yes,scrollbars=yes,width=550,height=300,status=no,resizable=yes,dependent=yes,alwaysRaised=yes");
            frm.action="/Comm/ms_makepdf.jsp";
            frm.target='comp_win';
            frm.submit();
        }

    function pdfwrite(frm)
    {if(_iseditmode)
            document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();

        var frm=document.frmtext;
        new_win = window.open('','new_win', 'menubar=no,scrollbars=yes,width=600,height=340,status=no,resizable=yes,top=200,left=200,dependent=yes,alwaysRaised=yes');
        new_win.opener = window;
        new_win.focus();

        frm.body.value=frm.txt.value;
        frm.action="/pdfWriter";
        frm.target='new_win';
        frm.submit();
    }
    function docxwrite(frm)
    {if(_iseditmode)
            document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();

        var frm=document.frmtext;
        new_win = window.open('','new_win', 'menubar=no,scrollbars=yes,width=600,height=340,status=no,resizable=yes,top=200,left=200,dependent=yes,alwaysRaised=yes');
        new_win.opener = window;
        new_win.focus();

        frm.body.value=frm.txt.value;
        frm.action="/docxWriter";
        
        frm.submit();
    }

    function showconv()
    {
        document.getElementById("saveinprogress").style.display="block";
        document.getElementById("sip").src="/images/saveinprogress.gif";
    }

    function switchlang(lang) {
        var url=location.href;
        if (url.indexOf("cmdlang")>-1)
            url=url.substring(0,url.indexOf("cmdlang"));
        url+="&cmdlang="+lang;
        location.href=url;
    }


    function gohtml(){
        if(_iseditmode)
            document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
        var frm=document.frmtext;
        var jsrc=getsrc();
        if(jsrc.length>0)
            frm.txt.value+="\<script language=javascript\>"+jsrc+"\</script\>";
        frm.body.value=frm.txt.value;
        frm.iswebpage.value="1";
        popupNote();
        frm.action="/s_viewpagehtml.jsp";
        frm.target='comp_win';
        window.open("", "comp_win", "menubar=yes,scrollbars=yes,width=736,height=700,status=no,resizable=yes,dependent=yes,alwaysRaised=yes");
        frm.submit();
        self.close();
    }

    function popupNote(){
        alert("Right click the new popup page and \"Save as\" a HTML file.");
    }

    function setfrmheight() {
		
        $("#page_win").height($("body").height() - ($("#header").height()));
    }

    </script>
    <script type="text/javascript" src="/js/ssfunctions.js?v=201711.05"></script>

    <style>
        html,body{
            height:100%;
            overflow: hidden;
        }
        body{
            min-width:100%;
            max-width:100%;
            width:100%;
        }
    </style>
</head>
<body scroll="no" onload="puttxt();setfrmheight();" onresize="setfrmheight();">

    <!--<div style="display:none;width:100%;height:100%;top:0;left:0;position:absolute;background:#FFFFFF;z-Index:200;opacity:0.8;filter:alpha(opacity=80);text-align:center" id="saveinprogress"><table height="100%" width="100%" cellspacing="0" cellpadding="0"><tr><td valign="middle" align="center"><img src='/images/blank.gif' id="sip"><br><strong style='font-size:16pt;color:#697F39'>PDF Creation in Progress</strong><br><strong style='font-size:12pt;color:#697F39'>Please Wait</strong></td></tr></table></div>-->
    <div style="display:none;width:100%;height:100%;top:0;left:0;position:absolute;background:#FFFFFF;z-Index:200;opacity:0.8;filter:alpha(opacity=80);text-align:center" id="saveinprogress"><table width="100%" height="100%" cellspacing="0" cellpadding="0"><tbody><tr><td valign="middle" align="center"><img src="/images/blank.gif" id="sip" alt="Save In Progress"><br><div style="font-size:16pt;font-weight:bold;color:#697F39" id="smsg">PDF Creation in Progress</div><br><strong style="font-size:12pt;color:#697F39">Please Wait</strong></td></tr></tbody></table></div>


    <div id="header">
        
        
        <table width="100%" cellspacing="0" cellpadding="0" border="0">
            <tbody><tr>
                <th class="Title">Web Page View Actions</th>
            </tr>
        </tbody></table>
        
        <form name="frmtext" target="page_win" action="s_savetextfile.jsp" method="POST">
        <input name="ss_formtoken" id="ss_formtoken" value="0A0133DEE42C7A11D0AA8C8988695CEDAA905422B38099B3C0C9B463CEDC7663" type="hidden">
        <input value="1127956" name="objectid" type="hidden">
        <input value="" name="folderid" type="hidden">
        <input value="0" name="peopleid" type="hidden">
        <input value="0" name="varcontactid" type="hidden">
        <input value="2" name="format" type="hidden">
        <input value="" name="pswd" type="hidden">
        <input value="1" name="peopletypeid" type="hidden">
        <input value="1" name="iswebpage" type="hidden">
        <input value="" name="body" type="hidden">
        <input value="" name="subject" type="hidden">
        <input value="" name="cc" type="hidden">
        <input value="0" name="touser" type="hidden">
        <input value="0" name="maxp" type="hidden">
        <input value="Examinee_Notice_1127956" name="pdfname" type="hidden">
        <input value="Examinee_Notice_1127956" name="filename" type="hidden">
        <input value="24" name="entity" type="hidden">
        <input value="102946" name="appid" type="hidden">
        
        <table width="100%" cellspacing="0" cellpadding="0" border="0">
            <tbody><tr>
                <td class="Title">

                    <table cellspacing="0" cellpadding="0" border="0">
                        <tbody><tr>
                            <td colspan="3">

                                
                                <input name="cmdedit" id="cmdedit" class="ButtonSm" value="Edit" onclick="editdoc(this)" type="button">
                                
                                <input name="cmdemailpdf" id="cmdemailpdf" style="display: inline;" class="ButtonSm" value="Email as PDF" onclick="emailpdf()" type="button">
                                
                                <input name="cmdpdf" id="cmdpdf" style="display: inline;" class="ButtonSm" value="Export as PDF" onclick="pdfwrite();" type="button">
                                

                            </td>
                        </tr>
                    </tbody></table>

                </td>
            </tr>
        </tbody></table>
        
        
        <table id="functable" name="functable" width="100%" cellspacing="0" cellpadding="0" border="0">
            <tbody><tr>
                <td class="Title">

                    <div style="float:right;padding:4px 4px 0 0">
                        
                        Folder Name: <select name="mfolderid" class="AppNav" style="max-width:300px"><option value=""> --Select a folder-- </option><option value="1267619">Active Drafts</option>
<option value="1267614">Active Medical File</option>
<option value="1269758">Adjuster Service Requests (ARF - Portal)</option>
<option value="1267610" selected="">Adjuster, Assessor, Examinee And Legal Rep Communications</option>
<option value="1267616">Archived Medical File</option>
<option value="1274156">Client Invoices</option>
<option value="1269519">Correspondence - Notice to Assessor forms &amp; Assessment Plans</option>
<option value="1267612">Correspondence - Other</option>
<option value="1267620">Final Reports</option>
<option value="1267615">IME Guidelines Kits</option>
<option value="1267621">Informed Consent</option>
<option value="1267623">Provider Invoices</option>
<option value="1269372">Invoices and Consents</option>
<option value="1269448">Medical Briefs and Insurer Examination Reports</option>
<option value="1273039">Previous Drafts</option>
<option value="1267609">Production and Court Prep</option>
<option value="1273836">Referral Mandate</option>
</select>

                        
                    </div>


                    
                    <input name="cmdsavepdf" class="Button" value="Save To Server as PDF" onclick="saveserver(1)" type="button">
                    



                </td>
            </tr>
        </tbody></table>
        

        <textarea cols="0" rows="0" name="txt" style="display:none">
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
   &lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
      &lt;title&gt;Claimant Notice&lt;/title&gt;
      &lt;style type="text/css"&gt;		
         Table td 
         {
         padding: 3px;  
         vertical-align: top;
         }
         body
         {
         font-size:10pt;font-family:arial;				
         }
      &lt;/style&gt;
      &lt;script language="JavaScript" src="/jquery/jquery.js?v=201711.05"&gt;&lt;/script&gt;
      &lt;style&gt;&lt;/style&gt;
      &lt;script type="text/javascript"&gt;
         $(document).ready(function(){                      
         alert('aaa');   
        $('#cmdedit').hide();   
         	}
         });
      &lt;/script&gt;
   &lt;/head&gt;

   &lt;body&gt;
      &lt;table width="700px" border="0" align="center" cellpadding="0" cellspacing="0"&gt;
         &lt;tbody&gt;
            &lt;tr&gt;
               &lt;td&gt;                    
                  Test Test						
               &lt;/td&gt;
            &lt;/tr&gt;
         &lt;/tbody&gt;
      &lt;/table&gt;
   &lt;/body&gt;
&lt;/html&gt;</textarea>

    </form>
    </div>
      <div class="iframe_ipad">
    <iframe src="/s_blank.html" id="page_win" name="page_win" style="height: 71px;" width="100%" frameborder="0"></iframe>
      </div>




</body></html>

3 个答案:

答案 0 :(得分:6)

您正尝试在cmdedit内执行的javascript代码中隐藏ID为<iframe>的元素。但是元素不在<iframe>里面,所以jQuery找不到它。

你需要告诉jQuery在哪里寻找元素。您可以通过将第二个参数传递给jQuery选择器来完成。来自jQuery Api documentation page

  

<强> jQuery( selector [, context ] )

     

<强>选择
  输入:Selector
  包含选择器表达式

的字符串      

<强>上下文
  输入:ElementjQuery
  要用作上下文的DOM元素,文档或jQuery
    -

所以你只需要传递顶部窗口文档对象来选择隐藏它的元素。

    $(function(){
        $("#cmdedit", window.top.document).hide()
    });
  

或者您可以使用主窗口的jQuery

window.top.$("#cmdedit").hide();
  

或者你可以使用普通的javascript

window.top.document.getElementById('cmdedit').style.display = 'none';

答案 1 :(得分:0)

试试这个

$('#cmdedit').css('display','none');
$('#cmdedit').css('height',0);
$('#cmdedit').css('width',0);
$('#cmdedit').css('visibility','hidden');
$('#cmdedit').css('position','fixed');

固定位置必须与隐藏的可见性结合使用,因此不会占用文档空间。

虽然不是最好的做法,但却是获得结果的第二种方式。

答案 2 :(得分:0)

尝试:

<script>
        $(window).ready(function(){
            $('#cmdedit').hide();
        });
    </script>

希望这有帮助。