HREF with https link in a frame doesn't work [duplicate] - html

I am trying to put google.com into an iframe on my website, this works with many other websites including yahoo. But it does not work with google as it just shows a blank iframe. Why does it not render? Are there any tricks to do that?
I have tried it in an usual way to show a website in an iframe like this:
<iframe name="I1" id="if1" width="100%"
height="254" style="visibility:visible"
src="http://www.google.com"></iframe>
The google.com page does not render in the iframe, it's just blank. What is going on?

The reason for this is, that Google is sending an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page.
See: Mozilla Developer Network - The X-Frame-Options response header

IT IS NOT IMPOSSIBLE.
Use a reverse proxy server to handle the Different-Origin-Problem. I used to using Nginx with proxy_pass to change the url of page. you can have a try.
Another way is to write a simple proxy page runs on server by yourself, just request from Google and output the result to the client.

As it has been outlined here, because Google is sending an "X-Frame-Options: SAMEORIGIN" response header you cannot simply set the src to "http://www.google.com" in a iframe.
If you want to embed Google into an iframe you can do what sudopeople suggested in a comment above and use a Google custom search link like the following. This worked great for me (left 'q=' blank to start with blank search).
<iframe id="if1" width="100%" height="254" style="visibility:visible" src="http://www.google.com/custom?q=&btnG=Search"></iframe>
EDIT:
This answer no longer works. For information, and instructions on how to replace an iframe search with a google custom search element check out:
https://support.google.com/customsearch/answer/2641279

You can use https://www.google.com/search?igu=1 instead of https://google.com/ , it works. This issue is it has X-Frame-Options Header policy and browsers follow those policies.

You can solve using Google CSE (Custom Searche Engine), which can be easily inserted into an iframe. You can create your own search engine, that search selected sites or also in entire Google's database.
The results can be styled as you prefer, also similar to Google style. Google CSE works with web and images search.
google.php
<script>
(function() {
var cx = 'xxxxxxxxxxxxxxxxxxxxxx';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only></gcse:searchresults-only>
yourpage.php
<iframe src="google.php?q=<?php echo urlencode('your query'); ?>"></iframe>

You can bypass X-Frame-Options in an using YQL.
var iframe = document.getElementsByTagName('iframe')[0];
var url = iframe.src;
var getData = function (data) {
if (data && data.query && data.query.results && data.query.results.resources && data.query.results.resources.content && data.query.results.resources.status == 200) loadHTML(data.query.results.resources.content);
else if (data && data.error && data.error.description) loadHTML(data.error.description);
else loadHTML('Error: Cannot load ' + url);
};
var loadURL = function (src) {
url = src;
var script = document.createElement('script');
script.src = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=getData';
document.body.appendChild(script);
};
var loadHTML = function (html) {
iframe.src = 'about:blank';
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html.replace(/<head>/i, '<head><base href="' + url + '"><scr' + 'ipt>document.addEventListener("click", function(e) { if(e.target && e.target.nodeName == "A") { e.preventDefault(); parent.loadURL(e.target.href); } });</scr' + 'ipt>'));
iframe.contentWindow.document.close();
}
loadURL(iframe.src);
<iframe src="http://www.google.co.in" width="500" height="300"></iframe>
Run it here: http://jsfiddle.net/2gou4yen/
Code from here: How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

If you are using PHP you can use file_get_contents() to print the content:
<?php
$page = file_get_contents('https://www.google.com');
echo $page;
?>
This will print whatever content file_get_contents() function gets in this url.
Please note that since you are displaying content as string instead as a actual web page, things like relative path images are not shown correctly, because /img/myimg.jpg is now loading from your server and not from google.com anymore.
However, you can play with some tricks like str_replace() function to replace absolute urls in images:
<?php
$page = file_get_contents('https://www.google.com');
echo str_replace('src="img/','src="https://google.com/img/',$page);
?>

This used to work because I used it to create custom Google searches with my own options. Google made changes on their end and broke my private customized search page :( No longer working sample below. It was very useful for complex search patterns.
<form method="get" action="http://www.google.com/search" target="main"><input name="q" value="" type="hidden"> <input name="q" size="40" maxlength="2000" value="" type="text">
web
I guess the better option is to just use Curl or similar.

Its not ideal but you can use a proxy server and it works fine. For example go to hidemyass.com put in www.google.com and put the link it goes to in an iframe and it works!

Related

How to embed MediaWiki page content into my site?

Our corporate wiki is Mediawiki. I have no problem to put iframe into my site to refer for some article on wiki.
But my own site have a lot of widgets and own style. I don't want to include Mediawiki navigation/search/login widgets, logo image.
Is it possible and how to get Mediawiki page contents without widgets (only article body)?
Yes, it is. You'll probably want to use the action=render url parameter, for example: http://en.wikipedia.org/w/index.php?action=render&title=Main_Page. Note that the stylesheets from the wiki aren't included, so you'll need to copy the relevant rules to your site's css files. See also this.
Thank waldir for answer!
After asking question I perform own research and end with code:
window.onload = function() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState !== 4) {
console.log("Not ready, code: %o", httpRequest.readyState);
return;
}
if (httpRequest.status !== 200) {
console.log("Server error: %o", httpRequest.status);
return;
}
var json = JSON.parse(httpRequest.responseText);
console.log("json: %o", json);
var wiki = json.query.pages["1"].revisions[0]["*"];
console.log("wiki: %o", wiki);
var html = InstaView.convert(wiki);
console.log("html: %o", html);
document.getElementById('area').innerHTML = html;
};
var url = 'https://wiki.evil-company.com/api.php?action=query&prop=revisions&format=json&titles=Main_page&rvprop=timestamp|user|comment|content';
httpRequest.open('GET', url, true);
httpRequest.send(null);
}
Here I use https://github.com/cscott/instaview/blob/master/main.js project which is enhanced http://en.wikipedia.org/wiki/User:Pilaf to transform json output to HTML on browser side.
The reason for this code because our wiki is old or misconfigured and action=render is not available. But I trap into cross-domain scripting issue so I think that iframe with action=render is better solution.
See also How do you grab an article including the links in a usable format?
Another suggestion to use action=parse (http://en.wikipedia.org/w/api.php?action=parse&title=Linux) lead to warning:
You are looking at the HTML representation of the XML format.
HTML is good for debugging, but is unsuitable for application use.
Specify the format parameter to change the output format.
UPDATE
Perfect solution just append query action=render to any valid wiki URL like:
http://en.wikipedia.org/wiki/Linux?action=render

In AS3 / Flash Can a URL Request / Loader Use "//" without Specifying a http or https Protocol?

I have a flash app running that loads remote data and we're transitioning to use (SSL) https://
I am wondering is it possible to just use "//" as you would in JavaScript to automatically assume the parent page's protocol (http or https).
Thanks
update: it seems to me that you can use a url format like "//www.something.com" but instead of assuming the page protocol it seems like it's just defaulting to "http://www.something.com".
Now I'm working around this by checking if the SWF is an SSL url. Something like this:
if( loaderInfo.url.indexOf("https:") == 0 ) {
//replace http: with https:
}
Which is unfortunately inconvenient to be doing that everywhere you handle a remote asset URL. Just loading everything with matching proto would be a lot nicer... like "//www.someurl.com/wouldbenicer.xml", especially since js and html both work that way.
Blah.
Any ideas?
"//" relative proto doesn't work in flash the way the browser works with urls in HTML, instead it defaults to http://
Workaround:
Check the URL of the SWF to see if the URL about to be loaded should be modified to have https:// protocol:
if( loaderInfo.url.indexOf("https:") == 0 ) {
//replace http: with https:
} else {
//replace https: with http:
}
Building upon OG Sean's answer, here's a wrapper function that'll manage protocol-relative URLs and default to HTTP.
function relativeURL(url:String) {
var scheme = (loaderInfo.url.indexOf("https:") == 0) ? "https:": "http:";
var url = scheme + url.replace(/^https?:/,"");
return url;
}
using a string contains splash, and add it twice
var singlesplash:String = "/";
var doublesplash:String = singlesplash + singlesplash;
myurl = "http:" + doublesplash + "www.google.com";
or
myurl = "http:/" + "/www.google.com";

Chrome addon with my server interaction

its many days reading hundreds of ways to help me make what I really need. No success at all.
What I need is this:
1) Having a button which only works when the tab has a certain url.
2) After clicking it, must read page's source and then get some pieces of it to send them to my server page in order to check my database for recordcounts (I assume with AJAX & javascript). Then this page should send back to the extension its responses and populate the popup html.
Looks easy I know, but please I need the workflow if not the required codes for the extension.
Thank you so much!
ok so you can chceck selected tab and it's url with:
chrome.tabs.getSelected(null,function(tab) {
workWithUrl(tab.url);
});
...
function workWithUrl(url){
if (url == ...
...
}
To be able to chceck this you need to add permission for "tabs"
To process page source code, send it to web service and change popup.html:
var xhr = new XMLHttpRequest();
xhr.open("POST", "__server adress___", true);
//headers
xhr.setRequestHeader("Content-Type", "application/json");
//response
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
//response from service to popup.html
document.body.innerHTML = xhr.responseText;
}
}
//process page here
xhr.send(pageText);
You have to add permission for server adress to manifest as well and everything should be executed from popup.js (or html).

Google App Scripts : Javascript code inside the HTML file not functioning

I have been trying to write a small Google App Script which has the Google+ badge as shown here. For this I have a plain HTML file where I have included the HTML as shown on that page. The HTML page is as follows :
<html>
<body>
<div class="g-plus" data-href="{Page-Link}" data-rel="publisher"></div>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
alert("Added Badge!");
})();
</script>
</body>
</html>
The result is a blank page. There is no badge added to the page . I assume this is because the javascript function is not being run( I added an alert and there wasnt any pop-up ).I am not able to figure out why the function is not being run.
Any help is appreciated.
Unfortunately I'm not too experienced with Javascript so I'm guessing here. I've programmed in coffeescript a while ago and its compiler automatically wraps the generated code in an anonimous function just as in your code. This function is called so:
(function() {//...}).call(this);
Maybe this works.
Alternatively you might want to move the alert test above the badge generation. This would show if the javascript is run at all. Maybe the error lies in your badge creation code.
My final idea would be to name your function and register it as a callback on body.onload . It's always a good idea to let the browser load the page before accessing the dom

Protecting iFrame - Only allow it to work on one domain

I have a Widget that I created and I am embedding it on other websites using an iFrame. What I want to do is make sure no one can view the source and copy the iFrame code and put it on their own website.
I can store the URL that it should be allowed on in the database. I've seen it done before, one site had a long encrypted code and if it didn't match with the domain then it said Access Denied..
Does anyone know how I can do this?
Thanks!
No you can't do this. The best thing you can do is the following:
if (window.top.location.host != "hostname") {
document.body.innerHTML = "Access Denied";
}
Add the above to your JavaScript and then use a JavaSript obfuscator
You cannot prevent people from looking at your HTML, but there are some headers can allow you to specify what sites can embed your iframe. Take a look at the X-Frame-Options header and the frame-ancestors directive of Content-Security-Policy. Browsers that respect it will refuse to load the iframe when embedded into someone else's site.
On the server in the code for the page displayed in the IFRAME, check the value of the Referer header. Unless this header has been blocked for privacy reasons, it contains the URL of the page which hosts the IFRAME.
What you are asking for is pretty much impossible. If you make the source available on the web someone can copy it one way or another. Any javascript tricks can be defeated by using low level tools like wget or curl.
So even if you protect it, you're still going to find that someone could in theory copy the code (as the browser would receive it) and could if so determined put it on their own website.
I faced the same problem, but I return the user on a home page. I spread the decision.
It has to be placed where there is iframe
<script>
$(window).load(function () {
var timetoEnd = '';
var dstHost = 'YOUR-ALLOW-HOST';
var backToUrl = 'BACK-TO-URL';
function checkHost(){
var win = window.frames.YOUR-IFRAME-NAME;
win.postMessage('checkHost', dstHost);
console.log('msg Sended');
clearInterval(timetoEnd);
timetoEnd = setInterval(function () {
window.location.href = backToUrl;
}, 5000);
}
function validHost(event) {
if (event.data == 'checkHostTrue') {
clearInterval(timetoEnd);
console.log('checkHostTrue');
} else {
return;
}
}
window.addEventListener("message", validHost, false);
checkHost();
setInterval(function () {
checkHost();
}, 10000
);
});
</script>
It has to be placed into your src iframe
<script>
function receiveMessage(event)
{
if(event.data=='checkHost'){
event.source.postMessage("checkHostTrue",
event.origin);
} else {
return;
}
}
window.addEventListener("message", receiveMessage, false);
</script>
I know it's kinda old topic but I have code that you just put in <script> tag and it should prevent most of curious people from looking at html files from iFrame:
if(window.top.location.pathname === window.location.pathname){
history.back()
}