Iframe Question - php

If I control the content of two pages (PageA and PageB), one of which I want to load into an iframe (PageB), is there some javascript I can enter on PageB that will pull a style from the parent (PageA)? I need two style options, one for when PageB is loaded in an iframe, and one for when PageB loads on its own.

A solution I could see is loading the styles for both files from an external file, and set the src attribute of the IFrame to include a GET variable as such (rest of this example assumes a file with the name index2.php):
<iframe src="index2.php?iframe=Y" ... />
From there, towards the top of index2.php should look something like this:
<?php
if ($_GET["iframe"] == "Y") {
echo "<link href='global.css' type='stylesheet' />";
} else {
echo "<link href='specific.css' type='stylesheet' />";
}
....
?>
While Kris' solution is also valid, I wouldn't and never do rely on Javascript to work the same in all browsers, regardless of whether it's been tested or not. At least this way, you know that the file is being loaded into an IFrame.

I would do it this way: check to see if your page is loaded in a frame or not and choose your styles based on this rather than attempting to pull styles from a parent page.
You can detect if you're in a frame via this type of code:
if ( top.location.href !== window.location.href ) { /* In frame */} else { /* Not in frame */ }

Related

Apply css to iframe wordpress [duplicate]

Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?
You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.
Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.
I use the Prototype framework to make it easier:
frame1.$('mydiv').style.border = '1px solid #000000'
or
frame1.$('mydiv').addClassName('withborder')
In short no.
You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.
Yes. Take a look at this other thread for details:
How to apply CSS to iframe?
const cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].contentWindow.document.body.appendChild(cssLink);
// ^frame1 is the #id of the iframe: <iframe id="frame1">
You can retrieve the contents of an iframe first and then use jQuery selectors against them as usual.
$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")
$("#iframe-id").contents().find("img").addClass("fancy-zoom")
$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });
Good Luck!
The quick answer is: No, sorry.
It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.
Use Jquery and wait till the source is loaded,
This is how I have achieved(Used angular interval, you can use javascript setInterval method):
var addCssToIframe = function() {
if ($('#myIframe').contents().find("head") != undefined) {
$('#myIframe')
.contents()
.find("head")
.append(
'<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
$interval.cancel(addCssInterval);
}
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);
Combining the different solutions, this is what worked for me.
$(document).ready(function () {
$('iframe').on('load', function() {
$("iframe").contents().find("#back-link").css("display", "none");
});
});
Apparently it can be done via jQuery:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
https://stackoverflow.com/a/13959836/1625795
probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.
Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine.
The only solution is to fetch the page from the server side code and change the needed CSS.
A sort of hack-ish way of doing things is like Eugene said. I ended up following his code and linking to my custom Css for the page. The problem for me was that, With a twitter timeline you have to do some sidestepping of twitter to override their code a smidgen. Now we have a rolling timeline with our css to it, I.E. Larger font, proper line height and making the scrollbar hidden for heights larger than their limits.
var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary
Just add this and all works well:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
If the iframe comes from another server, you will have CORS ERRORS like:
Uncaught DOMException: Blocked a frame with origin "https://your-site.com" from accessing a cross-origin frame.
Only in the case you have control of both pages, you can use https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage to safely send messages like this:
On you main site(one that loads the iframe):
const iframe = document.querySelector('#frame-id');
iframe.contentWindow.postMessage(/*any variable or object here*/, 'https://iframe-site.example.com');
on the iframe site:
// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
// Do we trust the sender of this message?
if (event.origin !== "http://your-main-site.com")
return;
...
...
});
Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.
References:
Printing content of IFRAME
Accessing and printing HTML source code using PHP or JavaScript
http://www.w3schools.com/js/js_htmldom_html.asp
http://www.w3schools.com/js/js_htmldom_css.asp

Conditional php include in wp using media queries and javascript

I may be going about this all wrong, but here goes.... Im trying to use JavaScript in a WP theme file to do conditional PHP includes based on CSS media queries and pseudo-elements.
In the CSS I use a media query to check for mobile devices in portrait mode, add a hidden :after element to the body under this query with content="mobile_portrait" attribute.
I then wanted to go on the homepage template and use JavaScript like this:
var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'mobile_portrait') {
<?php
add_action( 'genesis_after_header', 'do_this' );
function do_this() {
require(CHILD_DIR.'/do_this.php');
}
?>
}
else {
<?php
add_action( 'genesis_after_header', 'do_the_other' );
function do_the_other() {
require(CHILD_DIR.'/do_the_other.php');
}
?>
}
It seems like WP is skipping the JavaScript and parsing the PHP because if I take out the else it just loads do_this.php whether the Java check returns true or false, if I leave the else in, it breaks the site :(
Ideas about what im doing wrong? or a better way to load PHP files based on media queries?
Thanks in advance
PHP and Javascript cannot be used interchangeably like you are trying to do.
PHP is the renderer, it is building the output (building the Javascript)
The PHP will be run, regardless of where they are put inside a Javascript conditional like you have, as the Javascript conditionals have no bearing on them being executed.
==
Now to add a solution:
Maybe use the javascript like you have setup simply redirect to the phpfile you want to run for a given view:
var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'mobile_portrait') {
window.location = '<?= CHILD_DIR.'/do_this.php'; ?>';
}
else {
window.location = '<?= CHILD_DIR.'/do_the_other.php'; ?>';
}
So have different pages that do the necessary includes based on the media query

Suggestions for iframe which deliver content according to the parent url?

I hope someone can help me with this issue. So, I have a large website (1000+ webpages) and I want to put an iframe window on every page. My aim is to make this iframe load specific content according to the parent url address of each page on my website.
For example, when the user on my site loads www.mysite.com/Page-1, I want the iframe window to show ExternalPage-A, or when the user loads www.mysite.com/Page-2, I want the iframe to show ExternalPage-B.
Can someone give me an advise how to do it? Should I make a separate php document that will load in the iframe, where to put all the external links? Then, I should take somehow the parent url and tell the php document which link to be displayed. I am not very familiar with php and that is why I am asking.
Thanks!
Don't use $_SERVER['HTTP_REFERER'] because it won't always contain any data. This is set at the user's end, it cannot be trusted and isn't always set.
You would be better with your referring URL's and corresponding iframe URL's in a database. But putting a database to one side for a moment you could do something like this:
<?php
function get_iframe_url ($page) {
$page = parse_url ($page, PHP_URL_PATH);
/* Substitute the below IF statement for a database lookup
if you have lots of pages */
if ($page == '/news.php') {
return 'http://www.bbc.co.uk/news/';
} elseif ($page == '/contact.php') {
return 'http://www.yellowpages.com/';
}
}
?>
Then you can include this on every page:
<iframe src="<?php echo get_iframe_url ($_SERVER['REQUEST_URI']); ?>"></iframe>

How to make a dynamic php website with permanent links?

So i have a problem, I never did this before.
I have this website http://82.196.14.71/obrigatorionaover/ .
I want to generate ajax webpages but I want permanent links too for the browser history.
This is the body of the first page (releituras.php):
<body>
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/obrigatorionaover/php/nav.php";
include_once($path);
?>
<div id="float">
//this is a connect
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/obrigatorionaover/xxxxxxxxxxxx.php";
include_once($path);
?>
<?php
try {
$stmt = $db->query('SELECT * FROM sessoes ORDER BY id DESC');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<div style="background-image:url('."http://localhost:8888/obrigatorionaover/".$row["img"].')" class="rect sessao" id=sessao'.$row["id"].'>'.'<h3 class="titulo">'.$row["numero_sessao"].'</h3>'.'<p class="descricao">'.$row["descricao"].'</p>'.'</div>';
}
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
}
?>
</div>
<script src="/obrigatorionaover/js/script.js"></script>
</body>
I clean the div float and insert new content dynamically like this, (sessao.php is similar to the query from releituras.php)
function sessao(data){
$("#float").html("");
$.get("/obrigatorionaover/php/sessao.php?id=1").done(function(data) {
$("#float").append(data);
});
}
The url in the browser doesn't change, it is possible to change the url dynamically without changing the content?
The browser history doesn't change either (I know I can inject it but i don't have valid physic php page). How can I inject it? Should I create physic php pages automatically when inserting information into the database?
Can I have something like virtual php pages? If yes how to do it?
What you need - is to use HTML anchors together with ajax navigation.
When you load something with ajax, modify anchor. This will not reload page, but will give you really new window.location.
When page is loaded without ajax, parse that anchor (if exists) to determine what ajax page to display.
That is basic idea, a direction for your thoughts since I do not know the details of your project implementation.
Loading with AJAX and going to anchor in loaded content

Switchstyle Problem in Joomla/Php/Jquery/Css

I've been developing a site (for now is here as an example: http://neurotoxine.mine.nu/gloom), and I'm getting a strange behaviour from a styleswitcher code. It's big so please be patient.
First, you may go to the site I appointed first and see it.
What you've got there, it's a joomla page, with a Jquery using
var $j = jQuery.noConflict();
in order to avoid mootools conflicts.
Then, I used these:
<? // Checks for, and assigns cookie to local variable:
if(isset($_COOKIE['style']))
{ $style = $_COOKIE['style'];
}
// If no cookie is present then set style as "red" (default):
else { $style = 'red';
}
?>
This is just for the cookie setting, if the cookie is not set then $style=red, and this variable will be appended to the CSS. Like this:
<link rel="stylesheet" type="text/css" href="<?php echo $this->baseurl ?>/templates/wh1/css/template_<?php echo $style ?>.css" media="screen" />
The first code, $this->baseurl=directory for joomla installation, in this case gloom.
The second one, echo $style, will write the cookie loaded value or the value assigned from the options, in the case you get there for first time then you'll got RED as value then, template_red.css will be the CSS for the entire site.
There's a JS, that works doing some jquery tricks:
jQuery.fn.styleSwitcher = function(){
$j(this).click(function(){
// We're passing this element object through to the loadStyleSheet function.
loadStyleSheet(this);
// And then we're returning false.
return false;
});
function loadStyleSheet(obj) {
$j('#preloader')
// Now fade in the div (#preloader):
.fadeIn(500,function(){
// The following will happen when the div has finished fading in:
// Request PHP script (obj.href) with appended "js" query string item:
$j.get( obj.href+'&js',function(data){
// Select link element in HEAD of document (#stylesheet) and change href attribute:
$j('#stylesheet').attr('href','css/' + data + '.css');
// Check if new CSS StyleSheet has loaded:
cssDummy.check(function(){
// When StyleSheet has loaded, fade out and remove the #overlay div:
$j('#preloader').fadeOut(500);
});
});
});
}
// CSS DUMMY SECTION
var cssDummy = {
init: function(){
// Appends "dummy-element" div to body:
$j('<div id="dummy-element" style="display:none" />').appendTo('body');
},
check: function(callback) {
// Checks if computed width equals that which is defined in the StyleSheets (2px):
if ($j('#dummy-element').width()==2) callback();
// If it has not loaded yet then simple re-initiate this function every 200 milliseconds until it had loaded:
else setTimeout(function(){cssDummy.check(callback)}, 200);
}
}
cssDummy.init(); }
then, I start the function in my page:
$j(document).ready(function(){
$j('#style-switcher a').styleSwitcher();
});
and I call it from a link like this:
img
Finally, the styleswitcher.php code is here:
<?php
$style = $_GET['style'];
setcookie("style", $style, time()+604800*24); // 604800 = amount of seconds in one week *4=1 month *24=1/2 year *48=1 year
if(isset($_GET['js']))
echo $style;
else header("Location: ".$_SERVER["HTTP_REFERER"]); ?>
Now, the problem is, that when I tested this in a site, everything worked fine (http://neurotoxine.mine.nu/wht/index-test.php - The links for the stylechanger are in the top and left of them says THEMES). But when I inserted the whole code in joomla template, the whole system failed. I did some fixes here and there (mainly the $j declaration) and then I realized that could be something related to the path of the templates, so I tested many types of declarations, absolute paths, relative paths, etc. and nothing happens.
Then I copied styleswitcher.php to the root of joomla (neurotoxine.mine.nu/gloom) and checked if ti would work there, and I'm getting a blank page. I clicked go-back and then WOW the stylechanger worked, but then something isn't telling where to go back to I think it could be the header("Location: ".$_SERVER["HTTP_REFERER"]); instruction, but I don't know what to change there to make it work.
Joomla gives a declaration in the header for its templates:
<base href="http://neurotoxine.mine.nu/gloom/" />
I don't know if this is doing something to the way the http_referer works, but I disabled this and the site still does the same, click a style, page blank, hit go-back and voila, the style has changed but failed to retrieve the page where I was.
Some ideas? Any help could be useful.
The Referer is only set, when you click on a link (not when you enter it directly in the adress bar). In fact the browser tells the site where the user has been before clicking on this link, so you can't trust it to 100 % (see PHP Manual). I would store the last visited page in $_SESSION and redirect to this one; and if it is empty, redirect to $this->baseurl . '/index.php'.
The base-Tag is only needed for relative links, e.g.
<a href="index.php">
or even:
<a>
Another tip: Before taking the style from the cookie, check if it exists (either hardcode all available templates or file_exists()). If not, take the default one (red).
I resolved this... the solutions were fixing three to four errors:
first of all, the cookie checker in the html should have asked if the coockie wasn't empty, no if it was SET. So:
<?php // Checks for, and assigns cookie to local variable:
if(!empty($_COOKIE['style'])) $style = $_COOKIE['style'];
// If no cookie is present then set style as "red" (default):
else $style = 'red';
?>
That was the first thing to fix.
Then this line is fixed, because the JQuery plugin asked for an ID in the header to alter. I didn't realized I haven't an ID at the link stylesheet declaration
<link id="stylesheet" rel="stylesheet" type="text/css" href="<?php echo $this->baseurl ?>/templates/wh1/css/template_<?php echo $style ?>.css" media="screen" />
In this line I also discovered that
<?php echo $this->baseurl ?>
should be replaced with the base address but, without the domain, so it should be
/gloom/templates/wh1/css/template_<?php echo $style ?>.css
Also, in the initialization of the JQuery plugin, i made a fatal mistake. I didn't changed the ID for the container of the tag that was going to be captured by the plugin. That was in part for the confusion between the ID on the header for the stylesheet and the ID on the tag container. So I used "#tselect" for the ID of a DIV and it solved the Jquery work. Besides, is mandatory to ad $j in every statement of the plugin.
$j(document).ready(function(){
$j.preloadCssImages({statusTextEl: '#textStatus', statusBarEl: '#status'});
$j("img#hhead").toggle(
function () {
$j("#headtop").slideDown();
},
function () {
$j("#headtop").slideUp();
});
$j("#tselect a").styleSwitcher(); // here is the "ID TAG".plugin() call.
});
Now, in the styleswitcher.php I used a tip someone told me about the cookie:
<?php $style = $_GET['style'];
setcookie("style", $style, time()+604800,"/"); // 604800 = amount of seconds in one week
if(isset($_GET['js'])) echo $style;
else header("Location: ".$_SERVER['HTTP_REFERER']);
?>
Did you noticed? is a simple / slash.
Now everything works fine. The stylechanger changes the styles and the JQuery effects work.
You could see it here: link text
If anyone wants the files and an explanation, send me a message.

Categories