1

I'm trying to load iframe, and after it was loaded to inject to it my custom css style. But when I'm loading the page I see my css style appears for a split second and then the iframe finally loaded it overrides my style and it disappears.

I know, I need to wait until the iframe is loaded, and I tried to do so but without any success.

When I'm stopping debugger after execution of the following codeline, I can see the background changes. But then it disappears.

.append('<style> body{background:red;}</style>');

Look at the code snippet.

 (function(){
            var iFrame = $('iframe');
            var contents = iFrame.contents();
            var styleTag = contents.find('head').append('<style> body{background:red;}</style>'); 
        })();
#my-iframe {
            width: 100%;
            height: 600px;
        }
        
        #middle-container {
            width: 500px;
            margin-left: auto;
            margin-right: auto;
        }
        
        #iframe-container {
            width: 100%;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <title>iFrame Test Page</title>
</head>

<body>
    <div id="middle-container">
        <div id="iframe-container">
            <iframe id="my-iframe"       src="http://www.w3schools.com">
                <p>Sorry! Your browser doesn't support iFrames</p>
            </iframe>
        </div>
    </div>
</body>

</html>

1
  • 1
    did you try giving ! important on the css styles? Commented Jun 22, 2016 at 14:39

2 Answers 2

3

Your code is correct, actually. However, the content will never change and stay changed because you are trying to modify the content of an external resource. Cross-site scripting (security) rules in the browser prevent you from being able to achieve this.

The only way for you to edit the contents of an iframe is to replace the entire contents of the iframe.

Example:

$('iframe').load(function() {
  $('iframe').replaceWith('<p>Replacing everything!</p>');
});

But then it seems rather pointless.

Sign up to request clarification or add additional context in comments.

Comments

0

Why not use jQuery to change the color like this:

https://jsfiddle.net/9vzj7qt8/

 (function(){
            var iFrame = $('iframe');
            var contents = iFrame.contents();
            var styleTag = contents.find('body').css("background-color","red"); 
        })();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.