user1115666
user1115666

Reputation:

Apply css styles within the parent page to an iframe of the same domain

I'm trying to apply a stylesheet to the contents of an iframe from the parent - yes, I know there's been several questions asked in the past regarding this same idea, but I'm working within the same domain here and I've tried nearly every solution on this website and none of them have worked. Here's what I got:

<html>
<title>Untitled</title>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script type="text/javascript" media="screen">

    var cssLink = document.createElement("link") 
    cssLink.href = "http://domain.extension/style.css"; 
    cssLink .rel = "stylesheet"; 
    cssLink .type = "text/css"; 
    frames['#window'].document.body.appendChild(cssLink);

</script>

<style type="text/css" media="screen">

body {
    margin: 0px;
    padding: 0px;
    height: 100%;
}

iframe#window {
    padding: 0px;
    border: 0;
    width: 100%;
    height: 100%
}

</style>
</head>
<body>
    <iframe name="window" id="window" sandbox="allow-forms allow-scripts" src="http://domain.extension/example"/>
</body>
</html>

Upvotes: 0

Views: 7412

Answers (2)

teewuane
teewuane

Reputation: 5734

On both scripts (the one in the frame and the one in main window) you need to set document.domain to your domain. This needs to be before your $(document).ready() and such..

document.domain = "ra.gs";
var cssLink = $("<link/>",{
    href: "http://static.ra.gs/ttnnmnd/HFnmays5q/style.css",
    rel: "stylesheet",
    type: "text/css"
});

var iframeBody = $(window.document.frames["window"].window.document).contents().find("body");

iframeBody.prepend(cssLink);

Upvotes: 1

Qiang
Qiang

Reputation: 656

From what I know this is not possible due to sandboxing. Why not use AJAX? (Since this is on the same domain.)

To implement this, you could create a <div id="frame"></div> element and use the .load function to load the page into the div like this:

$('#frame').load('/somepage.html');

Upvotes: 1

Related Questions