How to cause an IFrame link to open into a new window? - javascript

I have a website which is built using WP and uses SSL. On one of the page on my website, I have added an iframe call to another http website.
Here is my iframe call:
<div class="embed-responsive embed-responsive-16by9">
<iframe src="//childwebsite.com/" target="_blank"></iframe>
</div>
The iframe is displayed properly. Now when you click on anything inside the iframe, Chrome displays a message saying
Mixed Content: The page at 'https://parentwebsite.com' was loaded over HTTPS, but requested an insecure resource 'http://childwebsite.com'. This request has been blocked; the content must be served over HTTPS.
What I am looking for is when a user clicks inside an iframe, open a new tab in the browser and let the user be redirected to a particular on the childwebsite.
I tried adding target="_blank" to the iframe but it did not work.
I added the following JS also but it did not work
//pass the iframe to this iframe getting function
function iframeRef( frameRef ) {
return frameRef.contentWindow ? frameRef.contentWindow.document : frameRef.contentDocument
}
//Get Iframe
var inside = iframeRef( document.getElementById('smugmugGallery') );
//Get all links
var links = inside.getElementsByTagName('input');
//Loop throught links and set their attributes
for (var i = 0 ; i<links.length ; i++){
links[i].setAttribute('target','_blank');
}
Any help will be appreciated.

You have two issues here. An SSL issue, and a cross domain issue.
Your SSL issue can only be solved by serving the iframed content via SSL or serving the parent page via non-SSL. This will remove the security alerts you are seeing.
You cannot assert control over iframed content if it comes from another domain, well at least not easily for cross browser purposes.
From the Mozilla dev site:
Scripts trying to access a frame's content are subject to the
same-origin policy, and cannot access most of the properties in the
other window object if it was loaded from a different domain. This
also applies to a script inside a frame trying to access its parent
window. Cross-domain communication can still be achieved with
window.postMessage.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#Scripting

Use base tag in iframe and try once.
<base target="_blank" />
you can see more about Base tag here

Related

Modifying width and height of a div element inside an iframe - cross domain policy

I have a domain and a subdomain. Domain is under my control, the subdomain is pointed to an affiliate whitelabel website, i.e. DNS points to their IP. I want to load the products through iframes on the domain.
I understand that I cannot use JavaScript to change the styling due to the cross domain policy. What I want to accomplish is to modify the height and width of a div deep inside the iframe.
Using a php simple load content is not working, because the page is heavily scripted, and if I am doing that, the framework of the page appears, yet no content is available.
Please point me to a practical solution? I know jquery enough to be able to replace, add styling to things on the same domain, iframe or not iframe. But I have no idea how to do it on the subdomain.
I can control the subdomain, ie I can change the dns back to what I want, but that will stop the whitelabel site from working. I can't add any headers.
The postMessage function should help you here, provided you can put your own JavaScript code on both domains.
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Something like this should work:
Parent
var iframe = document.getElementById("whatever");
iframe.contentWindow.postMessage("hello");
Iframe
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if (event.origin !== "http://your-parent-domain.com") return; // for security
// do something here with event.data
}

Communicating with the crossrider sidepanel plugin

The crossrider sidepanel is simply an iframe (you can use js-injected html, but I'm interested in using an iframe to reduce interference with the rest of the page). I'm having trouble getting any interaction between my browser extension and the iframe at all.
I see no point at all in adding a sidepanel with an extension unless you can do some basic JS communication. In this case I want a few options, checkboxes etc, in the iframe which control the extension. Since this plugin exists, I'm assuming there must be a way.
Ideally I'd like to have some basic input handling js in the child iframe and have it send back the odd save/load command. Is the answer really some form of message passing? If so which API should I be using here?
I believe this is related: Accessing iframe from chrome extension
[EDIT]
OK, so I've tried a few things...
It seems the expected usage is to host the iframe's html content somewhere. A bit strange considering it should be local and part of the extension. What happens if you want to view some pages offline?? This is just silly and I'm dismissing it as an option. Why waste resources hosting something that should just be available locally.
The alternative is to provide the HTML that goes in the sidebar. Note that this HTML doesn't get put in an iframe. I like the idea of an iframe because it keeps the CSS and JS very separate, so there's minimal interference between a page and your extension.
So I tried creating an iframe via the html sidebar attribute with and ID and injected the content after a 100ms delay using myiframe.contentWindow.document.open/writeln/close(). This works fine on chrome but fails in firefox with a security error (The operation is insecure on open()).
Another way is to provide the iframe content via the src url (for the sidebar I use a data address for the url attribute): Html code as IFRAME source rather than a URL. This works in firefox but results in a CORS error in chrome: The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match. and Warning: Blocked a frame with origin "http://localhost" from accessing a cross-origin frame. Function-name: appAPI.message.addListener
These CORS issues strike me as really daft. It's all my code coming from the same extension, injected into the same page. There's no cross origin happening, I created the damn thing. If I have the power to change the origin, then it's not secure in the first place so why bother.
Assuming you are using the url sidebar property to load your sidebar's HTML (i.e. a hosted web page), you can use the extension's Run in Iframe feature to communicate between the iframe extension and the parent window's extension.
To achieve this, first enable the extension to run in iframes (Settings > Run in Iframes) and then you can use the extension.js to load your sidebar and handle messaging. For example, the following code loads a page that has a button with identification btnSave:
Hosted web page file:
<html>
<head>
</head>
<body>
<div id="mySidebar">
My sidebar form
<br />
<button id="btnSave">Save</button>
</div>
</body>
</html>
extension.js file:
appAPI.ready(function($) {
// Check if running in iframe and the sidebar page loaded
if (appAPI.dom.isIframe() && $('#mySidebar').length) {
// Set click handler for button to send message to parent window
$('#btnSave').click(function() {
appAPI.message.toCurrentTabWindow({
type:'save',
data:'My save data'
});
});
// End of Iframe code ... exit
return;
}
// Parent window message listener
appAPI.message.addListener(function(msg) {
if (msg.type === 'save') {
console.log('Extn:: Parent received data: ' +
appAPI.JSON.stringify(msg.data));
}
});
// Create the sidebar
var sidebar = new appAPI.sidebar({
position:'right',
url: 'http://yourdomain.com/sidebar_page.html',
title:{
content:'Sidebar Title',
close:true
},
opacity:1.0,
width:'300px',
height:'650px',
preloader:true,
sticky:true,
slide:150,
openAction:['click', 'mouseover'],
closeAction:'click',
theme:'default',
scrollbars:false,
openOnInstall:true,
events:{
onShow:function () {
console.log("Extn:: Show sidebar event triggered");
},
onHide:function () {
console.log("Extn:: Hide sidebar event triggered");
}
}
});
});
However, if you are using the html sidebar property to load your sidebar's HTML, then this solution will not work since the extension does not run in this context. However, you may be able to utilize the methods described in the StackOverflow thread you quoted to communicate with the parent window (this would be browser specific) that in turn can communicate with the extension using our CrossriderAPI event.
[Disclaimer: I am a Crossrider employee]

How to open external url in iframe in angularjs?

How can i open youtube video link in iframe (or in colorbox, fancybox) with angularjs ?
It shows javascript error : "Refused to display document because display forbidden by X-Frame-Options."
Here is an Html code -
<a href="{{video_url}}" title="{{video.video_title}}" class="nyroModal">
{{video_title}}
</a>
javascript -
$('.nyroModal').nyroModal();
Clicking on above link, it should be opened in iframe .. But it shows error mentioned aboove.
Thanks.
You cannot control a parent frame, in this case, the browser) from a child iFrame across domains. This breaks the sandbox security of an iframe.
If you have access to both the parent and child frame's code and are on the same domain you could use the HTML5 postMessage() command.
For further reading on cross domain communication between iframes see the following:
http://softwareas.com/cross-domain-communication-with-iframes

Get content of an iframe after it loads with

I want to achieve the fallowing goal.I want by the click of a button to get the domain name entered in one input and load it into an iframe. What i have trouble with is after i load the specific site in the iframe how can i get the DOM of the loaded site in the iframe ? I need to save the exact path of an element of my choosing from the newly loaded site in the iframe by clicking on it. Any help would be much appreciated. Thank you.
You can access the <iframe>'s contents via the contentDocument property.
var iFrameContent = $('myIFrame')[0].contentDocument;
$(iFrameContent).find('.mySelector').text();
I should also point out accessing the <iframe>'s contents can only be done if the src of the <iframe> is from the same domain as your script. If the src of the <iframe> is from any other domain, the browser will deny access to the <iframe>contents.
This is a CORS consideration.
UPDATE:
To get around the CORS limitation, you'll have to write a server-side proxy for the URL that is the src of the <iframe> (and it could be pretty simple).
If I were to do something like this in ASP.Net (as an example), I would write a web service that:
takes the actual URL as a String parameter.
Uses the HTTPWebRequest object (or similar) to get the URL contents.
Return it back to the browser.
Then you could set your <iframe> src to "http://mysite.com/getURLService?url=www.lalala.com" and get the contents because the contents are now delivered by "http://mysite.com".
You use .contents()
like $("iframe").contents().find(); etc

iframe cross domain get CSS

I have an html page with css, I need the css to control the content of an iframe on that page. I have control of the page in the iframe and the following code works if both the page and frame are local to each other:
<script type="text/javascript">
window.onload = function() {
if (parent) {
var oHead = document.getElementsByTagName("head")[0];
var arrStyleSheets = parent.document.getElementsByTagName("style");
for (var i = 0; i < arrStyleSheets.length; i++)
oHead.appendChild(arrStyleSheets[i].cloneNode(true));
}
}
</script>
However does not work when the page with the iframe and the page the iframe is on are on separate domains. Does any one have any idea how I could get it to work across two domains, or have an alternative solution?
Thanks in advance :)
as it is my page that is displayed in iframe could I not just allow users to have their css override mine??
The site you load in the frame must grant you permission using CORS before you can instruct your visitors' browsers to exchange information between it and your site with JS. By default this is forbidden for sensible security reasons.
Add this HTTP Header on the target site:
Access-Control-Allow-Origin: *
See http://ox86.tumblr.com/post/17652823257/cross-domain-ajax-for-your-api-endpoints
You have to use Cross-document messaging. Basically, the algorithm should work something like this:
in the parent frame, add a message listener f before the iframe is loaded.
in the iframe, set up a message listener g and send a message to f after onload
f sends the CSS urls as a JSON-serialized message, and g loads the CSS into the iframe

Categories

Resources