top.opener.location.reload(true) not refreshing parent page on IE - javascript

I have two pages, the parent and from this page I am using:
window.open('OrderDetailsFull.aspx?ObjectID=' + ObjectID[1] , "TableDetails","status=0 , toolbar=0 , location=no , menubar=0 , scrollbars=yes , height=600px , width=800px");
to open a new window and manipulate data over there.
When I finish what I am doing I need the parent page to refresh so I will get the new data data in it...
From what I know the method is:
top.opener.location.reload(true);
but for some reason, it is not working in IE8 or IE9...
As I am building an application and not a general web page. It will work on Windows OS with IE (as for now it is still the most common system...nothing to do about it) so I really need to solve this problem....
I couldn't find any new solution over the web for this problem, every one say it should work like that.....
Did anyone encounter this problem? and does any one knows how to solve it?
OK, FOLLOW UP question: when I do opener.location.reload(true); does it render the parent page all over again (as it sound) or not? If it does then I'm in a big problem, if not, then there must be a way to do that...
The problem is the I have an ajax call in the parent page and for some reason it stays in it's old values when I am using it, only when I reload the child window, the parent ajax shows the real results, some code follows...
This is in the document ready jQuery function of the opener page:
$('div[id^="divTable"]').hover(
function(e){
//קבלת זהות השולחן הנלחץ
ObjectID = $(this).attr('id').split('_');
$(this).css("cursor","pointer");
//AJAX הבאת נתוני רשומת ההזמנה מהשרת ב
var OrderDetails = $.ajax({
url:'AjaxActions/OrderDetails.aspx?ObjectID=' + ObjectID[1],
async:false
}).responseText;
//צף מעל שולחן כשעומדים עליו, ניתן לראות את פרטי הרשומה של אותו השולחן DIV
$(this).append($('<div style="position: absolute; top: 0; left: -150;">' + OrderDetails + '</div>'));
//וידוא שהשולחן עליו אנו עומדים יהיה העליון
$(this).css("z-index","10");
$(this).siblings().css("z-index","1");
},
//כשיוצאים מהשולחן DIVהעלמת ה
function () {
$(this).find('div:last').remove()
}
);
This is in one of the functions in the child window that should refresh the opener:
$('#ctrl_Print').click(
function()
{
alert($('#hidItem').val());
var Items = new Array();
Items = $('#hidItem').val().split(',');
for(var i=0;i<Items.length;i++)
{
alert(Items[i]);
}
opener.location.reload(true);
window.location = 'OrderDetailsFull.aspx?OrderID=' + OrderID + '&ObjectID=' + ObjectID + '&Print=' + Items;
window.close();
}
);
10x...

It looks like IE 8 and 9 have security restrictions on refreshing the opener.

I've run into this problem where reload() works in Chrome, but pukes in IE.
Try using window.location.replace(your url and params here).
You have to collect the url and params for replace(), but it gets around the IE error message.
Example:
In Joomla 2.5 parent window launches modal for users input, where we need to reload the parent window (view) in order to run code that uses modal input.
The modal fires a function in the parent window like;
function updateAddresses(runUpdate, itemID, closeModal){
if(closeModal == true ){
SqueezeBox.close();
}
if(runUpdate == true){
//location.reload();
var replaceURL = 'index.php?option=com_poecom&view=cart&ItemId='+itemID;
window.location.replace(replaceURL);
}
}

top is used to get the outermost document within the current physical window when you're dealing with framesets and/or iframes and is not related to window.open in any way, so you shouldn't use top unless there are frames or iframes within your pop-up page. The following will do:
opener.location.reload(true);

If you want to access the parent window (or frame), you should use parent, not top:
parent.location.reload(true);
When your page is a frame inside that window, add more parents to it:
parent.parent.location.reload(true);

Related

What's this Javascript condition checking?

An ad provider wants us to add some Javascript to our site that'll allow them to resize the iframe their ad is served into. I've been going through the code, and part of it is this loop:
var topIframes = top.document.getElementsByTagName('IFRAME');
for (var i = 0; i < topIframes.length; i++) {
if (topIframes[i].contentWindow === self) {
// found iframe that served the ad
topIframes[i].style.height = sz + 'px';
}
}
I can see it's grabbing all the iframes in the document and adjusting the height of one or more of them. But I can't figure out what the condition's doing.
I know contentWindow's the window inside an iframe, and looking at What's the difference between self and window? I see that "self" is a reference to the window object. But which window object? The parent window or the window inside the iframe? Is there even a window inside the iframe? Why check that the window inside an iframe is the window inside an iframe?
////////////////////////////////////////////
EDIT
At Snuffleapagus's request, here's the long version:
<script type="text/javascript">
// iframe shrink function that needs to be on the hosting page
rp_resize = function (sz) {
try {
var topIframes = top.document.getElementsByTagName('IFRAME');
for (var i = 0; i < topIframes.length; i++) {
if (topIframes[i].contentWindow === self) {
// found iframe that served the ad
topIframes[i].style.height = sz + 'px';
}
}
} catch (e) {
}
}
</script>
<script>
// this is the code that goes in the passback to initiate the function
try {
if (typeof(rp_mpu) === 'function') {
rp_resize(250);
}
} catch (e) {
}
</script>
<script language="JavaScript" type="text/javascript">
rp_account = '<account-id>';
rp_site = '<site-id>';
rp_zonesize = '<zone-id>-<size-id>';
rp_adtype = 'js';
rp_smartfile = 'http://<url>/..../revv_smart_file.html'; // this should be the URL path to the friendly iframe that needs resizing
</script>
<script type="text/javascript" src="http://ads.<url>.com/ad/<account-id>.js"></script>
////////////////////////////////////////////
EDIT
Here's a possible clue from the ad provider in answer to my question about the condition. Don't know how much use it is, as he's not a developer.
"The line of code you are looking at is trying to determine if it is the iFrame from which the function has been initiated so it can be resized accordingly."
From what I understand working with Javascript and how it can access iFrames, the provider is assuming that you have multiple iFrames on the page. Also, it assumes that the iFrame they are looking for does not have an ID to reference easily.
Based on this, after the frame with the ad content loads, at some point it will call rp_resize(250);. However, the function rp_resize does not know which of the iFrames on the page it was called from. The script loops through all the iFrames on the page until it finds the one that called the function. This is how it knows which frame to call.
Hopefully that makes sense and / or answers your question.
I think, self refers to the parent window. To check, type the following in your browser console and see the result :
self == window
.contentWindow will return null if the iframe hasn't completely loaded. It looks like the code is looping through iframes, checking if they are loaded, and if so, resizing them.
Edit: musefan is right; I worded it incorrectly.
Edit 2: Why check that the window inside an iframe is the window inside an iframe? It's null if it's not loaded yet; if it is loaded, it's a window.

How can popup a window in a new URL but also shadow out the current window and prevent clicks (possibly with jQuery)

I am normally used to "window.open" to open a popup window into a new URL. How can open a window into a new URL, shadow out/grey out the current window, and on close remove the shadow background.
Is it best to use jQuery to do this? Could I use the default libraries without use jquery plugins?
I want to do something like this and then "disable" my shadow on unload. Hopefully that uses core jQuery libraries or standard javascript calls. I want to avoid using any plugins besides jQuery.
var popup = window.open('http://google.com', 'popup');
showShadow();
$(window).unload(function() {
if(!popup.closed) {
disableShadow();
}
});
Basically, you can open the popup and set that window the beforeunload. In short, something like this:
popup = window.open("", "name", "width=400, height=300")
popup.onbeforeunload = function() { $('#shadow').hide();}
I created a fiddle for you.
http://jsfiddle.net/DDksS/
So you want to build your own modal box using jQuery instead of using an existing plugin? ...OK, let's play (as it was already pointed out, using popups is not a user-friendly solution):
Your check list :
- the trigger
- the shadow layer
- the modal box size and position
- add content to modal and display it along the shadow
1) The trigger is a simple html link to open the content inside the modal
open url
... we will pass the size of the modal via data-width and data-height (HTML5) attributtes.
2) The shadow layer is the html structure that we will append to the body after the trigger. We can set the structure in a js variable
var shadow = "<div class='shadow'></div>";
3) As we mentioned, the size of the modal is set through some data-* attributes in the link. We would need to do some math
var modalWidth = $(this).data("width");
var modalHeight = $(this).data("height");
var modalX = (($(window).innerWidth()) - modalWidth) / 2; // left position
var modalY = (($(window).innerHeight()) - modalHeight) / 2; // top position
NOTE : $(this) is our trigger selector .myModal that we'll get inside an .on("click") method later on. BTW, the .on() method requires jQuery v1.7+
4) Now we need to create the modal's html structure and pass the content href. We'll create a function
function modal(url) {
return '<div id="modal"><a id="closeModal" title="close" href="javascript:;"><img src="http://findicons.com/files/icons/2212/carpelinx/64/fileclose.png" alt="close" /></a><iframe src="' + url + '"></iframe></div>';
}
... as you can see, our structure contains a close button to remove the modal and the shadow layer. The function also gets a parameter when is called (url) which allows to set the src attribute of the iframe tag.
NOTE : we have to use the iframe tag to open external urls, however we should always consider the same origin policy and other security restrictions when using iframes.
So now, we need to put together all the events after we click on our .myModal trigger, which are appending both the shadow and the modal box to the body and to remove them when we click on the close button so
$(".myModal").on("click", function(e) {
e.preventDefault();
// get size and position
modalWidth = $(this).data("width");
modalHeight = $(this).data("height");
modalX = (($(window).innerWidth()) - modalWidth) / 2;
modalY = (($(window).innerHeight()) - modalHeight) / 2;
// append shadow layer
$(shadow).prependTo("body").css({
"opacity": 0.7
});
// append modal (call modal() and pass url)
$(modal(this.href)).appendTo("body").css({
"top": modalY,
"left": modalX,
"width": modalWidth,
"height": modalHeight
});
// close and remove
$("#closeModal").on("click", function() {
$("#modal, .shadow").remove();
});
}); // on
STYLE : of course we will need some basic CSS style to make our modal elements work properly:
.shadow {width: 100%; height: 100%; position: fixed; background-color: #444; top: 0; left:0; z-index: 400}
#modal {z-index: 500; position: absolute; background: #fff; top: 50px;}
#modal iframe {width: 100%; height: 100%}
#closeModal {position: absolute; top: -15px; right: -15px; font-size: 0.8em; }
#closeModal img {width: 30px; height: 30px;}
* SEE DEMO *
BONUS : you could also bind a keyup event to close the modal using the escape key
$(document).keyup(function(event) {
if (event.keyCode === 27) {
$("#modal, .shadow").remove();
}
}); //keyup
LAST NOTE : the code is subject to many improvements and optimization but is a basic layout of what many lightboxes do. My last recommendation : use fancybox for more advanced functionality ... sometimes it doesn't worth the effort to re-invent the wheel ;)
Using Javascript to create new popup windows is so 1990's, not to mention not very user-friendly. What you're looking for, both UI-wise and looks-wise is a modal dialog; there's billions of examples and pre-packaged jquery snippets on how to create modal dialogs, and most client-side UI frameworks such as jQuery UI, YUI and Bootstrap have modal dialog functionality built-in. I'd recommend diving into those.
Try jquery plugins such as fancybox http://fancybox.net/
Basically, you need to attach an event listener to your new window to run the disableShadow() function in your webpage.
If you add this to your code I think it should work.
popup.unload(function() { disableShadow() });
Adapted From: Attach an onload handler on a window opened by Javascript
You should use the beforeUnload event of the window instance returned by the window.open() call, like this:
popup = window.open('relative_url', 'popup');
$(popup).bind('beforeunload', function() {
disableShadow();
});
Note that the URL must be on the same domain in order for the opener window to interact with the popup!
See the fiddle here: http://jsfiddle.net/hongaar/QCABh/
You can open a new window, and when it closes you can execute a function in the opener window.
I'll do a quick example by writing the script right into the new window, but you could also just include it in the HTML that is used for the new window if a link is supplied for the popup:
$("#popupBtn").on('click', openPopup); //using a button to open popup
function openPopup() {
$('#cover').fadeIn(400);
var left = ($(window).width()/2)-(200/2),
top = ($(window).height()/2)-(150/2),
pop = window.open ("", "popup", "width=400, height=300, top="+top+", left="+left),
html = '<!DOCTYPE html>';
html += '<head>';
html += '<title>My Popup</title>';
html += '<scr'+'ipt type="text/javascript">';
html += 'window.onbeforeunload = function() { window.opener.fadeoutBG(); }';
html += '</sc'+'ript>';
html += '</head>';
html += '<body bgcolor=black>';
html += '<center><b><h2 style="color: #fff;">Welcome to my most excellent popup!</h2></b></center><br><br>';
html += '<center><b><h2 style="color: #fff;">Now close me!</h2></b></center>';
html += '</body></html>';
pop.document.write(html);
}
window.fadeoutBG = function() { //function to call from popup
$('#cover').fadeOut(400);
}
Using a fixed cover that is faded in will also prevent any clicks on elements on the page, and you could even attach a click handler to the cover with pop.close() to close the popup if the cover is clicked, just like a modal would close if you clicked outside it.
One of the advantages of calling a function on the parent page from the popup is that values can be passed from the popup to the parent, and you can do a lot of stuff you otherwise could'nt.
FULLSCREEN_FIDDLE
FIDDLE
All you need is standard javascript function showModalDialog. Then your code will look like
var url = 'http://google.com';
showShadow();
var optionalReturnValue = showModalDialog(url);
//Following code will be executed AFTER you return (close) popup window/dialog
hideShadow();
UPDATE
As hongaar stated Opera does not like showModalDialog. And it does not fire on(before)unload when popup is closed either. To make workaround you need timer (window.setTimeout) to periodically check if window still exists. For further details look here
Why don't you just use jQuery UI? I know that you don't want another library but is rather extension of jQuery rather then another lib since it can live without it.
It have great deal of widget and every one of them can be changed,configured.
What is best that it can viewed with different themes, even you can create one with they're theme roller fast and easy, and it can be modularized. Just take what you need in current project.
Check this out:
http://jqueryui.com/dialog/#modal-form
It's really simple to use. With this you can open modal dialog with frame to different url. On close event you can do whatever you want.
Try ColorBox
its simple and easy to use
http://www.jacklmoore.com/colorbox
quick example:
<link rel="stylesheet" href="http://www.jacklmoore.com/colorbox/example1/colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://www.jacklmoore.com/colorbox/colorbox/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
//Examples of how to assign the ColorBox event to elements
$(".iframe").colorbox({iframe:true, width:"80%", height:"80%"});
});
</script>
<a class='iframe' href="http://google.com">Outside Webpage (Iframe)</a>
You can also try this out ...
http://fancyapps.com/fancybox/
Examples here
try http://thickbox.net/ in modal type, examples: http://thickbox.net/#examples
I've done this as well.
First off, some URLs simply WILL NOT WORK in an (iframe) modal window; I can't say if it'll work in the browser-supported native modal windows as I haven't tried this. Load google or facebook in an iframe, and see what happens.
Second, things like window onunload events don't always fire (as we've seen some people already).
The accepted answer version will also only work on a static page. Any reloading (even F5 on the page) will cause the shadow to hide. Since I can't comment on the accepted answer, I at least wanted this to be known for anyone else looking at these results.
I've taken a less technical approach to solving this problem in the past: polling.
http://jsfiddle.net/N8AqH/
<html>
<head>
<script type="text/javascript">
function openWindow(url)
{
var wnd = window.open(url);
var timer = null;
var poll = function()
{
if(wnd.closed) { alert('not opened'); clearInterval(timer); }
};
timer = setInterval(poll, 1000);
}
</script>
</head>
<body>
click me
</body>
</html>
See the link above for an example. I tested in IE, FF, and Chrome. My timer is every 1 second, but the effort on the browser is so low you could easily drop this down to 100 ms or so if you wanted it to feel more instant.
All you'd have to do in this example is, after calling window.open, call your "show shadow" function and instead of alerting when you close, call your "hide shadow" function and it should achieve what you're looking for.

Reload iframe src / location with new url not working in Safari

I have a page that loads with initially just a form within an iframe, something like this:
<iframe id="oIframe" ...src='somePage>'
<form ... />
</iframe>
When you click a button in the form, some javascript is invoked that builds a url and then I want to do the following:
frame.src = 'somePage?listId=1';
This works in IE to "reload" the frame with the new contents.
However, in Safari this does not work.
I have jQuery available, but I don't want to replace the existing iframe because there are events attached to it. I also can not modify the id of the iframe because it is referenced throughout the application.
I have seen some similar issues but no solutions that seem to work well for my exact issue.
Any assistance anyone can provide would be great!
Some browsers don't use "src" when calling the javascript object directly from the javascript hierarchy and others use "location" or "href" instead of "src" to change the url . You should try these two methods to update your iframe with a new url.
To prevent browser cache add a pseudo-random string like a number and timestamp to the url to prevent caching. For example add "new Date().getTime()" to your url.
Some calling examples:
document.getElementById(iframeId).src = url;
or
window.frames[iframeName].location = url;
I recommend the first option using document.getElementById
Also you can force the iframe to reload a page using
document.getElementById(iframeId).reload(true);
So the answer is very simple:
1. put a <div id="container"> </div> on your page
2. when reload needed use following jQuery:
$("#container").empty();
$("#container").append("<iframe src='" + url + "' />");
and that's it.
Of course there is more elegant way of creating DOM with jQuery but this gives the idea of "refreshing" iframe.
Works in FF18, CH24, IE9, O12 (well it's jQuery so it will work almost always :)
I found a better solution (albeit not paticularly eloquent) for this using jQuery.ajax:
jQuery.ajax({
type: 'GET',
url: "/somePage?someparms",
success: function() {
frameObj.src = "/somePage?someparms";
}
});
This forces the DOM to be read within the frame object, and reloads it once the server is ready to respond.
Try this
form.setAttribute('src', 'somePage?listId=1');
Well, I was able to find what appears to be a feasible solution -- it's a work in progress, but this is basically what I ended up doing:
var myFrame = document.getElementById('frame'); // get frame
myFrame.src = url; // set src attribute of original frame
var originalId = myFrame.id; // retain the original id of the frame
var newFrameId = myFrame.id + new Date().getTime(); // create a new id
var newFrame = "<iframe id=\"" + newFrameId + "\"/>"; // iframe string w/ new id
myFrameParent = myFrame.parentElement; // find parent of original iframe
myFrameParent.innerHTML = newFrame; // update innerHTML of parent
document.getElementById(newFrameId).id = originalId; // change id back
I ran into this issue using React, passing the key as props.src solved it
const KeyedIframe = ({children, ...props}) => <iframe key={props.src} { ...props}>
{children}
</iframe>

jquery thickbox reference problem

Completely restated my question:
Problem: Losing reference to an iFrame with Mozilla firefox 3.6 and 4.0
More info:
- Works fine in internet explorer 8 64-bit and 32-bit version.
How to reproduce? In Mozilla: Open the editor accordion menu. Click the 'editor openen' link, in the editor fill in some random text, then click 'bestand opslaan'. Fill in a name and click on 'save'. The content of the editor will be downloaded in HTML format.
Close the save file dialog box by clickin outside of it or on the specified buttons. Click on the 'bestand opslaan' button again and try to save your content to a file. You'll see nothing happening.
The problem isn't there in IE8. Try opening it in there.
Firebug tells me this the second time you open the save dialog:
iFrame.document is null
Example Link: http://www.newsletter.c-tz.nl/
More info:
- switched from thickbox to colorbox to try and resolve this issue and because thickbox isn't supported for a long time now.
- colorbox gives me the same problem so I don't think it is this.
- tried googling for iframe reference error and like, found nothing.
- tried putting the iframe code outside of the div that is called by the colorbox script, it retains it reference but not when I put it back inside that div.
Thanks to: JohnP who offered to open a 'hunt' on this.
Edit:
I thought maybe the saveFile.php file was causing trouble to the parent of the iframe but after removing it from the action variable in the editor.php script it still fails with the same error after you open the dialog for a second time.
Can someone maybe write a script that iterates through iframes by name and when the rignt iframe is found reference it to a var? I want to try it but don't know how..
I can't explain why it's work the first time for Firefox, but in Firefox the function to used for get iframe is different of IE : How to get the body's content of an iframe in Javascript?.
So, replace your JavaScript function "saveToFile" to this :
function saveToFile() {
var saveAsFileName = document.getElementById('saveAs_filename').value;
var currentContent = tinyMCE.editors["editor_textarea"].getContent();
var editorFileName = document.getElementById('editor_filename');
var iFrameTag = document.getElementById('saveAs_Iframe');
var iFrame;
if ( iFrameTag.contentDocument )
{ // FF
iFrame = iFrameTag.contentDocument;
}
else if ( iFrame.contentWindow )
{ // IE
iFrame = iFrameTag.contentWindow.document;
}
var inframeEditorFileName = iFrame.getElementById('editor_filename');
var inframeEditorContent = iFrame.getElementById('editor_textarea');
editorFileName.value = saveAsFileName;
inframeEditorFileName.value = saveAsFileName;
inframeEditorContent.value = currentContent;
iFrame.editor_self.submit();
}
I replace the function with Firebug and it's works for me.
Update :
You can also used a crossbrowser solution, more simple, thanks to jQuery :
function saveToFile() {
var saveAsFileName = document.getElementById('saveAs_filename').value;
var currentContent = tinyMCE.editors["editor_textarea"].getContent();
var editorFileName = document.getElementById('editor_filename');
editorFileName.value = saveAsFileName;
$("#saveAs_Iframe").contents().find("#editor_filename").val(saveAsFileName)
$("#saveAs_Iframe").contents().find("#editor_textarea").val(currentContent)
$("#saveAs_Iframe").contents().find("form[name=editor_self]").submit();
}

sending div to another page

i would like to send a div to another page actually im using javascript it work but i dont think its effecient cause it just show it it dont really send it, is there another way with ajax or jquery //my script send div:envoi to contenu.php under div:recu
function popWindow()
{
var pop = window.open('contenu.php'); self.focus();
if(pop.focus){ pop.focus(); }
}
function showIt() {
var cont = self.opener.document.getElementById('Envoi').innerHTML;
document.getElementById('recu').innerHTML = cont;
}
As far as I'm aware, that should work, assuming the showIt function is called within the popup window, within the onload event of the page body (or at some point after the 'recu' element have been drawn).

Categories