append element in head of an iframe using jquery

后端 未结 4 1744
刺人心
刺人心 2021-01-17 23:21

i want to append a style sheet(css) link to the head of an iframe using jquery . i tried with the following code but not working.

$(\'#tabsFrame\').contents(         


        
相关标签:
4条回答
  • 2021-01-18 00:00

    I believe you can't manipulate the content of an iframe because of security. Having you be able to do such a thing would make cross-site-scripting too easy.

    The iframe is totally seperate from the DOM of your page.

    Also, java and javascript are two completely different things!

    Follow the Link to see the difference here

    0 讨论(0)
  • 2021-01-18 00:09

    well, you can check with this:

    $('#tabsFrame').contents().find("head")[0].appendChild(cssLink);
    
    0 讨论(0)
  • 2021-01-18 00:15

    i am used to append data to an iframe by using this line of code

    $('body', window.frames[target].document).append(data);

    In your case, this line would look like this

    $('head', window.frames['tabsFrame'].document).append(cssLink);

    EDIT:

    Add <head></head> to the iframe and change your var cssLink to

    cssLink = '<link href="cupertino_1.4/css/cupertino/jquery-ui-1.8.7.custom.css" type="text/css" rel="Stylesheet" class="ui-theme" />

    0 讨论(0)
  • 2021-01-18 00:19

    This could be related to IE not allowing you to add elements in the DOM, check out the clever solution here

    EDIT:

    Thanks @kris, good advice to add more info in case links break:

    Here is the main code snippet from the link, in case it goes out again. (This is only needed with some IE version, for the most part, the other answer work just fine)

    var ifrm;
    
    //attempts to retrieve the IFrame document    
    function addElementToFrame(newStyle) {
        if (typeof ifrm == "undefined") {
            ifrm = document.getElementById('previewFrame');
            if (ifrm.contentWindow) {
                ifrm = ifrm.contentWindow;
            } else {
                if (ifrm.contentDocument.document) {
                    ifrm = ifrm.contentDocument.document;
                } else {
                    ifrm = ifrm.contentDocument;
                }
            }
        }
    
        //Now that we have the document, look for an existing style tag
        var tag = ifrm.document.getElementById("tempTag");
    
        //if you need to replace the existing tag, we first need to remove it
        if (typeof tag != "undefined" || tag != null) {
            $("#tempTag", ifrm.document).remove();
        }
    
        //add a new style tag
        $("HEAD", ifrm.document).append("");
    }
    
    0 讨论(0)
提交回复
热议问题