get the parent url of iframe in PHP - javascript

I am creating a widget that would load in a IFrame and users will be able to place the widget on their own website. How would I get the URL of the website that is using the IFrame in javascript and/or PHP? The IFrame loads a php file.
I have tried "parent.top.location.href" and "parent.document.referrer" in the IFrame page but that is undefined.
I have also tried to echo "$_Server[referrer]" in the IFrame page and that did return the IFrame parent URL, but how easy is it for someone to manipulate the referrer variable? I dont want to get misleading information.
The Goal: I created a widget and want to allow registered users to use that widget on their site. I want to be able to find out who is using the widget and if a un-registered user is using it on their site, then the widget would not display

I have also tried to echo
"$_Server[referrer]" in the IFrame
page and that did return the IFrame
parent URL, but how easy is it for
someone to manipulate the referrer
variable?
Pretty easy, but so is disabling JavaScript! However, if a web site uses your <iframe> it will be a little difficult for them to fake the referrer in their visitor's UA. (They could also proxy your content if they really insist on hiding the fact that they're using your content. In that case your only choice is not to publish it in the first place.)
In order to present content for "partners" only you could consider providing them with a token (like Twitter/Google/... APIs). If no (or an invalid) token is used, present an error. If a valid token is used but the referrer is suspicious you should investigate further.

Try with:
parent.location.href;
or
parent.document.URL

You can use the following PHP code to have the parent window URL get values in an array:
<?php
//Getting the parent window parameters
$getURLVar = str_replace("?","",strrchr($_SERVER['HTTP_REFERER'],"?"));
$getURLVar = str_replace("&","=",$getURLVar);
$getURLVar = str_getcsv($getURLVar,"=");
$i=0;
foreach ($getURLVar as $value)
{
if ($i % 2)
$value1[$i]=$value;
else
$value2[$i]=$value;
$i++;
}
$getURLVar =array_combine($value2,$value1);
print_r($getURLVar);
?>

A small piece of JavaScript in the iframe-d page can 'un-frame' the page:
if (top != self) {top.location.replace(self.location.href);}
Otherwise, as #mck89 says: the iframe can access the URL of the parent page using the top.location.href.
Further reading on the question How to prevent my site page to be loaded via 3rd party site frame of iframe.

Assuming your widget's URL doesn't do any redirects, etc., you should be able to use:
document.referrer
from within the javascript inside your iframe and it should contain the URL of the parent page. This seems to be what YouTube does for tracking in their iframe embed codes.

I would use:
$qStr = explode('?', $_SERVER['HTTP_REFERER']);
$t= explode('&', $qStr[1]);
foreach ($t as $val)
{
$a = explode('=', $val);
$args[$a[0]]=$a[1];
}
// to check the arguments
print_r($args);
// to check the url
echo $qStr[0];
$args would contain my security token which would be checked by some hashing against the url

Related

Get current object URL with JavaScript

I have a webpage uses object that are external websites (or other web pages).
for example:
<object data="external.html"></object>
on this page (external.html), the URL changes according to the navigation of the user. I want to know if there's a way to get the new URL using JavaScript/jQuery.
For example, when using:
<object data="www.google.com"></object>
If the user went from www.google.com to www.google.com/#q=JavaScript, I would like to get the second URL.
This won't work with Google, but theoretically speaking.
Alternatively, is there a way to display an external website and have access to the changing URL? Meaning, having a div populated by another website and somehow get the URL (after the user navigated through the site and the URL changes) with JavaScript/jQuery/some other way?
No need to manipulate this URL, just read access.
You can collect current URL using location.href and then collect object using its ID and then append data as current URL to it.
This should not possible as it will violate cross domain security policies. The same restriction is there with iframe, so I guess it applies to object as well.
If it is same domain, you can try getting the current URL from contentWindow or contentDocument
<objectElement>.contentWindow.location.href
Hope this is what you are looking for. You can split the url.
$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>
$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>

Set Iframe Source on Remote Page via URL Parameter

I have 3 pages that I am working with.
shop_mobile.php
This page retrieves product data from MySQL db and lists formats it. It accepts the url parameters brand=BRANDNAME and cat=CATEGORY.
Here are two examples of this page in action:
http://solanocycle.com/shop_mobile.php?brand=KYMCO&cat=KYMCO%20Scooters
http://solanocycle.com/shop_mobile.php?brand=peacesports&cat=Peace%20Sports%20Scooter
vehicles.html
This page contains links to view specific product listings pages (i.e. "KYMCO Scooters", "Peace Sports Scooters"). When these links are clicked, they should all take the user to the same page (view.html) but pass URL parameters which tell the Iframe within view.html which url to use as its source.
view.html
This page contains an Iframe which gets its source from the URL parameters passed by the links from vehicles.html
Note:
I tried using the solution provided at How do I pass URL parameter to an iFrame in Wordpress page? to solve my problem, but I have never used jquery before and I was not able to get it working correctly.
Any help would be greatly appreciated.
More Info
Sample of a link from Vehicles.html
KYMCO Scooters
What I think View.html should do:
Extract "http://solanocycle.com/shop_mobile.php?brand=KYMCO&cat=KYMCO%20Scooters" from the url "view.html?http://solanocycle.com/shop_mobile.php?brand=KYMCO&cat=KYMCO%20Scooters" and store it as a variable called $embedLink.
Display an Iframe with $embedLink as its source url.
Assuming your link(s) on vehicles.html are well structured, as follows:
view.html?url=http://solanocycle.com/shop_mobile.php?brand=KYMCO&cat=KYMCO%20Scooters
The necessary jQuery for view.html would be:
<script type="text/javascript">
$(document).ready(function(){
var regex = /\?url=(.*)/,
$embedLink = document.location.href.match(regex)[1];
$('iframe').attr('src', $embedLink);
});
</script>
Obviously you would replace 'iframe' with an id or class of the iframe to be more specific.
The alternate would be to use php to extract the request parameter and echo it out in place of the iframe's src attribute:
<?php $embedLink = (isset($_GET['url']) ? $_GET['url'] : ''); ?>
<iframe src="<?php echo $embedLink; ?>"></iframe>
I would recommend performing sanitisation of the request parameter in both cases in order to prevent XSS.

Open link to specific domain within an iFrame in a new window

I need to be able to open a link to a specific URL that is within an iFrame; the link is generated by php and I can't change the source code, so I need to change the link in the iFrame dynamically, if possible.
What I'm doing is this: on a non-profit organization's site, I have an affiliate store (generated by php) displayed within an iFrame on a page in order to make it more styled with the rest of the site. The php store pulls products from an affiliate service; the link to the store.php is in the same domain as the main non-profit's site.
The problem is the final "Buy Now" link from a product opens the final destination e-commerce store within the iFrame, and as such the page is stuck in the iFrame and looks bad and one must scroll V and H to see it and check out.
The link I need to open in a new window always has the class "av_buy_now" I have access to the CSS file, which I can change. I have access to the PHP files, i.e. shop.php, but it doesn't appear that the final link is generated locally. I'm showing the iframe this way:
<iframe src="http://nonprofit.org/shop/mj/shop.php"></iframe>
Is it possible to use jQuery or Javascript to find the links to mydomain.com with that one class and add a new window attribute to them? Or is there a better way? Thanks
Without some code I don't know the exact structure of your code, but I this could do the job. It requires jQuery to be in the iframe too.
$('iframe')[0].$('.av_buy_now').filter(function() {
return $(this).attr('href').indexOf('mydomain.com') > -1;
}).attr('target', '_blank');
You can change it if some how you can manage to execute this kind of code, changing class is little troublesome, of you got an id on it do something like this.
PAGE.html:
<button onclick="openinnewwin()">Get It</button>
<iframe src="test.html" id="ifrm"></iframe>
<script language="javascript">
function openinnewwin(){
ob=document.getElementById('ifrm');
if ( ob.contentDocument ) {
ob.contentDocument.getElementById('a').target="_blank";
}else if ( ob.contentWindow ){
ob.contentWindow.getElementById('a').target="_blank";
}
}
</script>
test.html:
Hello

iframe query string

I have got the values by passing the query string in an iframe.src = "xyxz.jsp?name="+name+"&pass="+pass+"&id="+id.
I need to pass those values which i have got to another jsp page
<iframe src="xyz.jsp"></iframe>
How can i do that?
Your question is unclear, but I guess that you want to pass the querystring of the parent JSP page to the JSP page which is in an iframe of the parent JSP page. If so, then just print HttpServletRequest#getQueryString():
<iframe src="page.jsp?${pageContext.request.queryString}"></iframe>
That said, iframes are an extremely bad practice and very clumsy when all the pages are located at the same server. Rather use server side includes using <jsp:include>. This way the included JSP has access to the same request object.
Use Javascript to dynamically change the src attribute of frame
function changeSrc()
{
window.frames['testframe'].src = "xyxz.jsp?name="+name+"&pass="+pass+"&id="+id;
}
Is this what are you looking for?
according to your cooment to #Manjoor post you want to call javascript function which is defined inside iframe and pass the parameters to it, if that so check this post
Invoking JavaScript code in an iframe from the parent page

Javascript Iframe innerHTML

Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:
document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML
etc
I think this is what you want:
window.frames['iframe01'].document.body.innerHTML
EDIT:
I have it on good authority that this won't work in Chrome and Firefox although it works perfectly in IE, which is where I tested it. In retrospect, that was a big mistake
This will work:
window.frames[0].document.body.innerHTML
I understand that this isn't exactly what was asked but don't want to delete the answer because I think it has a place.
I like #ravz's jquery answer below.
Having something like the following would work.
<iframe id = "testframe" onload = populateIframe(this.id);></iframe>
// The following function should be inside a script tag
function populateIframe(id) {
var text = "This is a Test"
var iframe = document.getElementById(id);
var doc;
if(iframe.contentDocument) {
doc = iframe.contentDocument;
} else {
doc = iframe.contentWindow.document;
}
doc.body.innerHTML = text;
}
If you take a look at JQuery, you can do something like:
<iframe id="my_iframe" ...></iframe>
$('#my_iframe').contents().find('html').html();
This is assuming that your iframe parent and child reside on the same server, due to the Same Origin Policy in Javascript.
Conroy's answer was right. In the case you need only stuff from body tag, just use:
$('#my_iframe').contents().find('body').html();
You can use the contentDocument or contentWindow property for that purpose.
Here is the sample code.
function gethtml() {
const x = document.getElementById("myframe")
const y = x.contentWindow || x.contentDocument
const z = y.document ? y.document : y
alert(z.body.innerHTML)
}
here, myframe is the id of your iframe.
Note: You can't extract the content out of an iframe from a src outside you domain.
Don't forget that you can not cross domains because of security.
So if this is the case, you should use JSON.
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
document.getElementById('iframe01').outerHTML
You can get the source from another domain if you install the ForceCORS filter on Firefox. When you turn on this filter, it will bypass the security feature in the browser and your script will work even if you try to read another webpage. For example, you could open FoxNews.com in an iframe and then read its source. The reason modern web brwosers deny this ability by default is because if the other domain includes a piece of JavaScript and you're reading that and displaying it on your page, it could contain malicious code and pose a security threat. So, whenever you're displaying data from another domain on your page, you must beware of this real threat and implement a way to filter out all JavaScript code from your text before you're going to display it. Remember, when a supposed piece of raw text contains some code enclosed within script tags, they won't show up when you display it on your page, nevertheless they will run! So, realize this is a threat.
http://www-jo.se/f.pfleger/forcecors
You can get html out of an iframe using this code
iframe = document.getElementById('frame');
innerHtml = iframe.contentDocument.documentElement.innerHTML

Categories