jquery iframe a links into new div / tab / window? - javascript

I have a tricky question.
All pages are within same server / portal.
I have a page that embeds iframe from the other page using the following code:
$('#mydiv').append('<p id="loading">Loading ...</p>');
$('#mydiv').append('<iframe id="myframe" name="myframe" class="myframe" onload="myframe()" style="display:none;"></iframe>');
$('#myframe').attr('src', 'https://mywebsite.com/page2');
function myframe() {
var $myframesearch = $('#myframe').contents();
$myframesearch.find("a").attr('target','_parent');
}
$('#myframe').load(function(){
$('#loading').remove();
$('#myframe').fadeIn();
});
All of the links within iframe have no href (but href="javascript:void(0)") and uses scripts within iframe to process the action dynamically.
Some links does open in new window some does not.
I would like to force all links to either open in new Tab, Window, or append to new Div, but none of the methods work, like base / parent, onclick / new window, _top, _parent, etc.
However, my idea was to hide and wait till the content of iframe is loaded after a click and then to append loaded content in new hidden div and then fade it in. When doing so the loaded iframe content resets back to default and not with new content.
Does anyone knows how this can be solved?
Thank you all!

So I check and it appears that other JavaScript overwrites the "a" tag action with some "data" field in the tag only for the "a" tags that contain "Open:" in their link.
I found solution to the problem below by the link for this "a" tag from another page bypassing the JavaScript overwriting:
$(function(){
$('#mydiv').append('<p id="loading">Loading ...</p>');
$('#mydiv').append('<iframe id="myframe" name="myframe" class="myframe" src="https://mywebsite.com/page2" onload="myframe()" style="display:none;"></iframe>');
$('#myframe').load(function(){
$('#loading').hide();
$('#myframe').fadeIn();
});
$('<div id="popup" style="display:none; width:1px; height:1px; position:absolute; top:0; left:0;"></div>').appendTo('html');
});
function myframe() {
var $myframesearch = $('#myframe').contents();
$myframesearch.find("a").attr('target','_parent');
$myframesearch.find('a:contains("Open:")').on('click',function(){
$(this).attr('data','');
var $texta = $(this).text();
var $text = $texta.replace(/Open: /,"");
$('#popup').load('https://mywebsite.com/page2' + ' a:contains("'+$text+'")', function(){
$('#popup a').each(function(){
this.href = this.href.replace(/https:\/\/mywebsite\.com\/page2\/a/, "https://mywebsite.com/page2");
this.click();
});
});
});
}
Hope this helps :)

Related

Iframe content empty in firefox

Info before reading: this code is written in vanilla js / jquery.
I have a page with a product list with infinite products and I want to scroll a bit down, click a product, go to that product detail page and when I click the browser back button it sends me to the list page at the same height where I was scrolling. So basically a pain to set up without a framework to keep track of state.
I've managed to get a POC for this appending an iframe with the product details content page and place it "on top" of the page. This, however, does not work in Firefox. Does anyone have any idea why?
I thought it was a z-index issue, however the iframe's body is empty. This is the iframe in Firefox:
<iframe id="productDetails" class="ProductDetailsFrame js-product-details-frame" src="http://localhost:3000/ProductDetailPage.html?productId=1888" scrolling="yes" frameborder="0">
#document
<html>
<head></head>
<body></body>
</html>
</iframe>
Here is the function I use to append the iframe:
(...)
function getBaseUrl() {
var re = new RegExp(/^.*\//);
return re.exec(window.location.href);
}
(...)
urlRoot = getBaseUrl()[0];
productLoadedUrl = urlRoot + 'ProductDetailPage.html?productId=' + productId;
(...)
function addIframe() {
$('<iframe>', {
src: productLoadedUrl,
id: 'productDetails',
class: 'ProductDetailsFrame js-product-details-frame',
frameborder: 0,
scrolling: 'yes'
}).appendTo($body);
}

How do I execute javascript only relative to that frame and not the whole window?

I have the following iFrame:
<div id="sandbox-inner">
<iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts" frameborder="0" name="Output " id="output" src="JavaScript:''"></iframe>
</div>
And when the user clicks to run their code, it injects the javascript successfully within this iframe. However, it actually runs it across the whole window, not just the iframe. So basically if I add a class "test" to an element outside the iframe, and one inside, and then inject the following inside the head of the iframe...
$(function() {
$('.test').css({ background: "blue" });
});
It effects my element outside the iframe too, which I really dont want. I need the iFrame to be a completely seperate environment. This is how I am currently injecting the javascript:
$('#runGuestCode').on("click", function () {
var js = $('#js-input').val(),
iframe = $("#output"),
iframeHead = iframe.contents().find("head").first(),
frame = document.getElementById("output"),
scriptTag = '<script>' + js + '<\/script>';
$('#output').contents().find("head").append(scriptTag);
});
Many thanks
UPDATE #1
The javascript is taken from textarea #js-input, which is whatever the user has typed. This is then appended to the head of the iframe, but currently runs relative to the parent document, not the iframe document.
You can do it following way, it will not effect you current page elements will apply to iframe element only:-
var iframe = $('iframe');
$(element, iframe.contents()).css({'background':'blue'});
Working Fiddle
Showcase the javascript code put by user in iframe:
$('#submit1').click(function (e) {
e.preventDefault();
var myIframe = document.getElementById("resultFrame");
var s = document.createElement("script");
s.type = "text/javascript";
s.innerHTML = $("#textarea1").val();
myIframe.contentWindow.document.head.appendChild(s);
});
Working Fiddle with Javascript Output in iframe

Gray and disable out the parent window as soon as pop up window is opened

I am trying to disable the Parent window as soon as the child window is opened. I would like to gray out the parent window whenever pop window is opened.
Below is my popup window code-
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var variable1 = getUrlVars()["parameter1"];
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
</script>
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="window.location.href='some_url'">
</body>
</html>
Below is my Parent window code-
<html>
<body>
<SCRIPT LANGUAGE="JavaScript">
<!--
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=650,left = 570,top = 300');");
}
</script>
<input type=button value="Apply" onClick="javascript:popUp('popup_window_url')">
</body>
</html>
What's the best and easy way to disable the parent window here? Any example with my above code will help me a lot in understanding a simple example.
I saw various other post on the stackoverflow but I am not able to understand how to incorporate those things here in my code. I am trying to do something like this.
Any suggestions will be of great help.
Updated fiddle from answer in this question with iframe support http://jsfiddle.net/LT5JC/
Open function is rather simple
function open(url) {
$('#block').fadeIn(); // show grayed pane
$('#iframe').attr('src', url); // update src of iframe
$('#container').fadeIn(); // show container with iframe
}
The example you gave doesn't use a popup in the sense of a new browser window, but a div on the existing page onto which the new content is loaded. This method is possible, as you would use an Ajax call to populate your popup. By using an Ajax call to the second page, you are able to tell when the request has finished, and fade the background out as required. If you really want to, you could use an iFrame, and check when that's loaded, but in my opinion this method isn't as nice.
A simple implementation using jQuery:
var cover = $("<div id='cover'></div>");
var content = $("#content"),
popup_window = $("#popup-window"),
popup_launcher = $("#popup-launch");
// When we click a button, load our new content into our popup
// and fade the window in once the request has completed. Also,
// fade our cover in, thus restricting the user from clicking the content beneath
popup_launcher.on("click", function() {
popup_window.load(child_url, function() {
popup_window.fadeIn();
content.fadeIn(cover);
});
});
// When a close button is clicked inside the popup window, fade it out.
popup_window.on("click", ".close", function() {
popup_window.fadeOut();
cover.fadeOut();
});
CSS
#cover {
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
z-index:2;
display:none;
background:RGBA(0,0,0,0.5);
}
#popup-window {
position:fixed;
left:30%;
right:30%;
top:30%;
bottom:30%;
z-index:3;
}
Very simple example, but our #cover has to be positioned beneath our #popup-window, so we use the z-index property to ensure this.
Edit - whilst the Ajax method would be nicer, bear in mind that due to HTTP access control, you'll only be able to request pages on the same domain (generally), so if you need to open external resources, you'll probably need to use an iFrame solution.

Create iframes from original page content with jQuery

I am trying to dynamically "rewrite" an entire page to a set of iframes. I want a music player bar at the bottom iframe and the original page "rewritten" in an iframe above/behind that. Almost just like SMC player. I feel like I'm close but I am a jQuery novice.. So any pointers will be greatly appreciated beforehand.
Here's the main part that creates the iframes that's not working correctly.
var oldpage = "<html>" + $("html").html() + "</html>";
$('body').html( "<iframe frameborder='0' id='content' allowtransparency='true' name='content'></iframe>" );
$('#content').contents().find('html').html(oldpage);
$('body').append("<iframe id='stratus' allowtransparency='true' frameborder='0' scrolling='0'>");
I'm trying to load the entire original html on line 1. Then creating iframes and trying to inject the oldbody variable into the new iframe #content. The iframes are created but the #content iframe has a blank body.
I don't know why, but you can't replace the whole HTML element, only its contents:
// create raw frame
var frame = $('<iframe id="maincontent" style="position:absolute; top: 0; left: 0; width: 50%; height: 50%;"><html></html></iframe>');
// store a copy of current document contents
var copiedHead = $('head').clone();
var copiedBody = $('body').clone();
// empty the current document
$(':not(iframe) body *').remove();
// load the copy into the frame;
// it's not possible to replace the whole HTML element;
// using plain JS DOM function here, since jQuery would strip out any SCRIPT and STYLE tags
frame.load(function(){
$(this).contents().find('html')[0].replaceChild(copiedHead[0] , $(this).contents().find('head')[0]);
$(this).contents().find('html')[0].replaceChild(copiedBody[0] , $(this).contents().find('body')[0]);
}).appendTo('body');

How do I use colorbox to show hidden divs on my page without hardcoding?

I'm using Colorbox to show the html content of hidden divs on my page. I can get this to work perfectly with the following:
$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});
This will show the div with the ID of 344.
However, because I'm trying to build a scalable and dynamic page with WordPress, I want to be able to grab the ID of my divs through a function, rather than hard code them in the jquery call.
I modified Jack Moore's example:
$("a[rel='example']").colorbox({title: function(){
var url = $(this).attr('href');
return 'Open In New Window';
}});
so that it looks like this:
$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
var elementID = $(this).attr('id');
return elementID;
}});
The problem with this is that the href property of the colorbox function is looking for a string with a # mark infront of the ID. I tried various ways of concatenating the # to the front of the function, including the # in the return value, and concatenating the # to the elementID variable. No luck.
I also tried using the syntax in Jack's example (with no luck) so that my return statement looked like this:
return "#'+elementID+'";
I think my basic question is: How do I use colorbox to show hidden divs on my page without hardcoding everything?
Thanks for your help,
Jiert
I didn't really like any of the answers given above. This is how I did it (similar but not quite the same).
I also fully commented it for people a bit new to Javascript and the colorbox plug in.
$(document).ready(function() { //waits until the DOM has finished loading
if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
$('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
$(url).hide(); //hides the lightbox content div
$(this).colorbox({
inline:true, // so it knows that it's looking for an internal href
href:url, // tells it which content to show
width:"70%",
onOpen:function(){ //triggers a callback when the lightbox opens
$(url).show(); //when the lightbox opens, show the content div
},
onCleanup:function(){
$(url).hide(); //hides the content div when the lightbox closes
}
}).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
//you could also use "return false" for the same effect but I proffered that way
})
}
});
And this is the html:
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
I think it would work with multiple lightboxes on the one page but I haven't tested it with that.
I'm facing the same issue. What does your html look like? meaning, how did you structure your "divs"
Mine looks like this:
Javascript:
<script>
$(document).ready(function () {
$("a.colorbox").colorbox({ width: "50%", inline: true, href: function () {
var elementID = $(this).attr('id');
return "#" + elementID;
}
});
});
</script>
And the html looks like (I tried changing the display:none):
<a class='colorbox' href="#">Inline HTML</a>
<div style="display:none">
<div id="pop">
This data is to be displayed in colorbox
</div>
</div>
return "#" + elementID;
will have the desired effect as David says.
This is the way I got it to work
HTML: (taken from the example in one of the answers)
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
Javascript:
$('a.lightboxTrigger').click(function(){
var ref = $(this).attr("href");
$.colorbox({ html: $(ref).html() });
$.colorbox.resize();
});

Categories