How can I make window.showmodaldialog work in chrome 37? - javascript

We have a huge web application where we use window.showmodaldialog for alerts, confirmations and popups. Since Chrome version 37 this call has been disabled.
Is there any quick workaround to make window.showmodaldialog work in the latest version of Chrome?
I am adding here a workaround for window.showmodaldialog, although this is not a perfect workaround because this will not break the code execution as showmodaldialog was doing, instead this will open the popups.
window.showModalDialog = function (url, arg, feature) {
var opFeature = feature.split(";");
var featuresArray = new Array()
if (document.all) {
for (var i = 0; i < opFeature.length - 1; i++) {
var f = opFeature[i].split("=");
featuresArray[f[0]] = f[1];
}
}
else {
for (var i = 0; i < opFeature.length - 1; i++) {
var f = opFeature[i].split(":");
featuresArray[f[0].toString().trim().toLowerCase()] = f[1].toString().trim();
}
}
var h = "200px", w = "400px", l = "100px", t = "100px", r = "yes", c = "yes", s = "no";
if (featuresArray["dialogheight"]) h = featuresArray["dialogheight"];
if (featuresArray["dialogwidth"]) w = featuresArray["dialogwidth"];
if (featuresArray["dialogleft"]) l = featuresArray["dialogleft"];
if (featuresArray["dialogtop"]) t = featuresArray["dialogtop"];
if (featuresArray["resizable"]) r = featuresArray["resizable"];
if (featuresArray["center"]) c = featuresArray["center"];
if (featuresArray["status"]) s = featuresArray["status"];
var modelFeature = "height = " + h + ",width = " + w + ",left=" + l + ",top=" + t + ",model=yes,alwaysRaised=yes" + ",resizable= " + r + ",celter=" + c + ",status=" + s;
var model = window.open(url, "", modelFeature, null);
model.dialogArguments = arg;
}
Just put this code in the head section of page.

I put the following javascript in the page header and it seems to work. It detects when the browser does not support showModalDialog and attaches a custom method that uses window.open, parses the dialog specs (height, width, scroll, etc.), centers on opener and sets focus back to the window (if focus is lost). Also, it uses the URL as the window name so that a new window is not opened each time. If you are passing window args to the modal you will need to write some additional code to fix that. The popup is not modal but at least you don't have to change a lot of code. Might need some work for your circumstances.
<script type="text/javascript">
// fix for deprecated method in Chrome 37
if (!window.showModalDialog) {
window.showModalDialog = function (arg1, arg2, arg3) {
var w;
var h;
var resizable = "no";
var scroll = "no";
var status = "no";
// get the modal specs
var mdattrs = arg3.split(";");
for (i = 0; i < mdattrs.length; i++) {
var mdattr = mdattrs[i].split(":");
var n = mdattr[0];
var v = mdattr[1];
if (n) { n = n.trim().toLowerCase(); }
if (v) { v = v.trim().toLowerCase(); }
if (n == "dialogheight") {
h = v.replace("px", "");
} else if (n == "dialogwidth") {
w = v.replace("px", "");
} else if (n == "resizable") {
resizable = v;
} else if (n == "scroll") {
scroll = v;
} else if (n == "status") {
status = v;
}
}
var left = window.screenX + (window.outerWidth / 2) - (w / 2);
var top = window.screenY + (window.outerHeight / 2) - (h / 2);
var targetWin = window.open(arg1, arg1, 'toolbar=no, location=no, directories=no, status=' + status + ', menubar=no, scrollbars=' + scroll + ', resizable=' + resizable + ', copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
targetWin.focus();
};
}
</script>

From http://codecorner.galanter.net/2014/09/02/reenable-showmodaldialog-in-chrome/
It's deprecated by design. You can re-enable showModalDialog support, but only temporarily – until May of 2015. Use this time to create alternative solutions.
Here’s how to do it in Chrome for Windows. Open Registry Editor (regedit) and create following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\EnableDeprecatedWebPlatformFeatures
Under the EnableDeprecatedWebPlatformFeatures key create a string value with name 1 and value of ShowModalDialog_EffectiveUntil20150430. To verify that the policy is enabled, visit chrome://policy URL.
UPDATE: If the above didn’t work for you here’s another method to try.
Download Chrome ADM templates from http://www.chromium.org/administrators/policy-templates
Extract and import policy relevant to your locale (e.g. windows\adm\en-US\chrome.adm. You can import either via gpedit.mscor using these utilities on Home editions of windows: http://blogs.technet.com/b/fdcc/archive/2008/05/07/lgpo-utilities.aspx)
Under “Adminstrative Templates” locate Google Chrome template and enable “Enable Deprecated Web Platform Feautes”.
Open the feature and add “ShowModalDialog_EffectiveUntil20150430″ key.

A very good, and working, javascript solution is provided here :
https://github.com/niutech/showModalDialog
I personnally used it, works like before for other browser and it creates a new dialog for chrome browser.
Here is an example on how to use it :
function handleReturnValue(returnValue) {
if (returnValue !== undefined) {
// do what you want
}
}
var myCallback = function (returnValue) { // callback for chrome usage
handleReturnValue(returnValue);
};
var returnValue = window.showModalDialog('someUrl', 'someDialogTitle', 'someDialogParams', myCallback);
handleReturnValue(returnValue); // for other browsers except Chrome

This article (Why is window.showModalDialog deprecated? What to use instead?) seems to suggest that showModalDialog has been deprecated.

The window.returnValue property does not work directly when you are opening a window using window.open() while it does work when you are using window.showModalDialog()
So in your case you have two options to achieve what you are trying to do.
Option 1 - Using window.showModalDialog()
In your parent page
var answer = window.showModalDialog(<your page and other arguments>)
if (answer == 1)
{ do some thing with answer }
and inside your child page you can make use of the window.returnValue directly like
window.returnValue = 'value that you want to return';
showModalDialog halts the executions of the JavaScript until the dialog box is closed and can get a return value from the opened dialog box when its closing.But the problem with showModalDialog is that it is not supported on many modern browsers. In contrast window.open just opens a window asynchronously (User can access both the parent window and the opened window). And the JavaScript execution will continue immediately. Which bring us to Option 2
Option 2 - Using window.open()
In your parent page write a function that deals with opening of your dialog.
function openDialog(url, width, height, callback){
if(window.showModalDialog){
options = 'dialogHeight: '+ height + '; dialogWidth: '+ width + '; scroll=no'
var returnValue = window.showModalDialog(url,this,options);
callback(returnValue)
}
else {
options ='toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=yes, scrollbars=no, width=' + width + ', height=' + height;
var childWindow = window.open(url,"",options);
$(childWindow).on('unload',function(){
if (childWindow.isOpened == null) {
childWindow.isOpened = 1;
}
else {
if(callback){
callback(childWindow.returnValue);
}
}
});
}
}
And whenever you want to use open a dialog. Write a callback that deals with the return value and pass it as a parameter to openDialog function
function callback(returnValue){
if(returnValue){
do something nice with the returnValue
}}
And when calling the function
openDialog(<your page>, 'width px', 'height px', callbak);
Check out an article on how to replace window.showModalDialog with window.open

I wouldn't try to temporarily enable a deprecated feature. According to the MDN documentation for showModalDialog, there's already a polyfill available on Github.
I just used that to add windows.showModalDialog to a legacy enterprise application as a userscript, but you can obviously also add it in the head of the HTML if you have access to the source.

I use a polyfill that seem to do a good job.
https://github.com/niutech/showModalDialog
http://niutech.github.io/showModalDialog/demo.html

Create a cross browser ModalDialog
function _showModalDialog(url, width, height, closeCallback) {
var modalDiv,
dialogPrefix = window.showModalDialog ? 'dialog' : '',
unit = 'px',
maximized = width === true || height === true,
w = width || 600,
h = height || 500,
border = 5,
taskbar = 40, // windows taskbar
header = 20,
x,
y;
if (maximized) {
x = 0;
y = 0;
w = screen.width;
h = screen.height;
} else {
x = window.screenX + (screen.width / 2) - (w / 2) - (border * 2);
y = window.screenY + (screen.height / 2) - (h / 2) - taskbar - border;
}
var features = [
'toolbar=no',
'location=no',
'directories=no',
'status=no',
'menubar=no',
'scrollbars=no',
'resizable=no',
'copyhistory=no',
'center=yes',
dialogPrefix + 'width=' + w + unit,
dialogPrefix + 'height=' + h + unit,
dialogPrefix + 'top=' + y + unit,
dialogPrefix + 'left=' + x + unit
],
showModal = function (context) {
if (context) {
modalDiv = context.document.createElement('div');
modalDiv.style.cssText = 'top:0;right:0;bottom:0;left:0;position:absolute;z-index:50000;';
modalDiv.onclick = function () {
if (context.focus) {
context.focus();
}
return false;
}
window.top.document.body.appendChild(modalDiv);
}
},
removeModal = function () {
if (modalDiv) {
modalDiv.onclick = null;
modalDiv.parentNode.removeChild(modalDiv);
modalDiv = null;
}
};
// IE
if (window.showModalDialog) {
window.showModalDialog(url, null, features.join(';') + ';');
if (closeCallback) {
closeCallback();
}
// Other browsers
} else {
var win = window.open(url, '', features.join(','));
if (maximized) {
win.moveTo(0, 0);
}
// When charging the window.
var onLoadFn = function () {
showModal(this);
},
// When you close the window.
unLoadFn = function () {
window.clearInterval(interval);
if (closeCallback) {
closeCallback();
}
removeModal();
},
// When you refresh the context that caught the window.
beforeUnloadAndCloseFn = function () {
try {
unLoadFn();
}
finally {
win.close();
}
};
if (win) {
// Create a task to check if the window was closed.
var interval = window.setInterval(function () {
try {
if (win == null || win.closed) {
unLoadFn();
}
} catch (e) { }
}, 500);
if (win.addEventListener) {
win.addEventListener('load', onLoadFn, false);
} else {
win.attachEvent('load', onLoadFn);
}
window.addEventListener('beforeunload', beforeUnloadAndCloseFn, false);
}
}
}

(function() {
window.spawn = window.spawn || function(gen) {
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = gen();
var onFulfilled = continuer.bind(continuer, 'next');
var onRejected = continuer.bind(continuer, 'throw');
return onFulfilled();
};
window.showModalDialog = window.showModalDialog || function(url, arg, opt) {
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
var caller = showModalDialog.caller.toString();
var dialog = document.body.appendChild(document.createElement('dialog'));
dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
dialog.innerHTML = '×<iframe id="dialog-body" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.getElementById('dialog-close').addEventListener('click', function(e) {
e.preventDefault();
dialog.close();
});
dialog.showModal();
//if using yield
if(caller.indexOf('yield') >= 0) {
return new Promise(function(resolve, reject) {
dialog.addEventListener('close', function() {
var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
document.body.removeChild(dialog);
resolve(returnValue);
});
});
}
//if using eval
var isNext = false;
var nextStmts = caller.split('\n').filter(function(stmt) {
if(isNext || stmt.indexOf('showModalDialog(') >= 0)
return isNext = true;
return false;
});
dialog.addEventListener('close', function() {
var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
document.body.removeChild(dialog);
nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
eval('{\n' + nextStmts.join('\n'));
});
throw 'Execution stopped until showModalDialog is closed';
};
})()
;
**Explanation:
------------**
The best way to deal with showModalDialog for older application conversions is use to `https://github.com/niutech/showModalDialog` inorder to work with show modal dialogs and if modal dailog has ajax calls you need to create object and set the parameters of function to object and pass below...before that check for browser and set the useragent...example: agentStr = navigator.userAgent; and then check for chrome
var objAcceptReject={}; // create empty object and set the parameters to object and send to the other functions as dialog when opened in chrome breaks the functionality
function rejectClick(index, transferId) {
objAcceptReject.index=index;
objAcceptReject.transferId=transferId;
agentStr = navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0) // If Internet Explorer, return version number
{
var ret = window.showModalDialog("/abc.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");
if (ret=="true") {
doSomeClick(index);
}
} else if ((agentStr.indexOf("Chrome")) >- 1){
spawn(function() {
var ret = window.showModalDialog("/abcd.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");
if (ret=="true") {// create an object and store values in objects and send as parameters
doSomeClick(objAcceptReject.index);
}
});
}
else {
var ret = window.showModalDialog("/xtz.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");
if (ret=="true") {
doSomeClick(index);
}
}

The window.showModalDialog is deprecated (Intent to Remove:
window.showModalDialog(), Removing showModalDialog from the Web
platform). [...]The latest plan is to land the showModalDialog removal
in Chromium 37. This means the feature will be gone in Opera 24 and
Chrome 37, both of which should be released in September.[...]

Yes, It's deprecated. Spent yesterday rewriting code to use Window.open and PostMessage instead.

Related

How to show multiple dialog polyfill?

I have script to open dialog polyfill :
window.modalDialog = function (url, arg, opt) {
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
var caller = modalDialog.caller.toString();
var dialog = document.body.appendChild(document.createElement('dialog'));
var splitter = opt.split(",");
dialog.setAttribute('style', splitter[0].replace(/dialog/gi, ''));
dialog.innerHTML = '×<iframe id="dialog-body" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.getElementById('dialog-close').addEventListener('click', function (e) {
e.preventDefault();
dialog.close();
});
dialog = document.querySelector('dialog');
dialogPolyfill.registerDialog(dialog);
function addListeners() {
document.querySelector('dialog').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp()
{
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e) {
window.addEventListener('mousemove', divMove, true);
}
function divMove(e) {
var div = document.querySelector('dialog');
div.style.position = 'absolute';
div.style.top = e.clientY + 'px';
div.style.left = e.clientX + 'px';
}
addListeners();
dialog.showModal();
dialog.addEventListener('close', function () {
var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
document.body.removeChild(dialog);
nextStmts[0] = nextStmts[0].replace(/(window\.)?modalDialog\(.*\)/g, JSON.stringify(returnValue));
eval('{\n' + nextStmts.join('\n'));
});
throw 'Execution stopped until modalDialog is closed';
};
when I call this script, dialog-body got replaced with new url instead create new dialog. How can i create multiple dialog?
EDIT
My biggest problem is that my dialogs has the same parent (caller), so in dialog polyfill js library, there's script to check if there are dialogs or not in parent document, if yes, then throw warning Failed to execute showModal on dialog: The element is already open, and therefore cannot be opened modally.
EDIT
I have created the jsfiddle, but i dont know how to call external source website from jsfiddle.
https://jsfiddle.net/godofrayer/gvLpLjkq/
I modified your example a little bit and now you can open multiple dialogs.
The problem was the getElementById. An id has to be unique in a document. So I have organized the dialogs in an array, and the ID-elements now contain the index of the array at the the end of the id: id="dialog-close'+dlgIndex+'".
My modification is here
Here you can see the main changes:
var dlgs = [];
window.showModalDialog = window.showModalDialog || function(url, arg, opt) {
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
var caller = showModalDialog.caller.toString();
var dialog = document.body.appendChild(document.createElement('dialog'));
// Adds the Dialog to an Array of Dialogs
var dlgIndex = dlgs.length;
dlgs[dlgIndex] = dialog;
dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
dialog.innerHTML = '×<iframe id="dialog-body'+dlgIndex+'" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
document.getElementById('dialog-body'+dlgIndex).contentWindow.dialogArguments = arg;
document.getElementById('dialog-close'+dlgIndex).addEventListener('click', function(e) {
e.preventDefault();
dialog.close();
});
dialog.showModal();
//if using yield
if(caller.indexOf('yield') >= 0) {
return new Promise(function(resolve, reject) {
dialog.addEventListener('close', function() {
var returnValue = document.getElementById('dialog-body'+dlgIndex).contentWindow.returnValue;
document.body.removeChild(dialog);
resolve(returnValue);
});
});
}
//if using eval
var isNext = false;
var nextStmts = caller.split('\n').filter(function(stmt) {
if(isNext || stmt.indexOf('showModalDialog(') >= 0)
return isNext = true;
return false;
});
dialog.addEventListener('close', function() {
var returnValue = document.getElementById('dialog-body'+dlgIndex).contentWindow.returnValue;
document.body.removeChild(dialog);
nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
eval('{\n' + nextStmts.join('\n'));
});
//throw 'Execution stopped until showModalDialog is closed';
};
})();
var showDialog = function() {
window.showModalDialog("https://heise.de/");
console.log("ShowSecond!!!")
window.showModalDialog("https://www.heise.de/newsticker/meldung/Einstweilige-Verfuegung-Vodafone-muss-Kinox-to-sperren-3966023.html");
};
Hope this helps.

Odoo discuss module change behaviour of scrollbar via javascript

The default behaviour of the discuss module in Odoo 9 is:
Last message at the bottom
Scrollbar at the bottom
I need to change this behaviour to:
Last message on top
Scrollbar on top
I think all this can be changed in odoo/addons/mail/static/src/js/thread.js
The order of messages is changed with:
init: function (parent, options) {
this._super.apply(this, arguments);
this.options = _.defaults(options || {}, {
//display_order: ORDER.ASC,
display_order: ORDER.DESC,
display_needactions: true,
display_stars: true,
display_document_link: true,
display_avatar: true,
shorten_messages: true,
squash_close_messages: true,
display_reply_icon: false,
});
this.expanded_msg_ids = [];
this.selected_id = null;
},
But then the user always has to scroll up so I also need to modify the behaviour of the scrollbar.
In this thread: Set scroll position I found it could be done with:
window.scrollTo(0, 0); // values are x,y-offset
or
var el = document.getElementById("myel"); // Or whatever method to get the element
// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;
This is some code I found in odoo/addons/mail/static/src/js/thread.js:
/**
* Scrolls the thread to a given message or offset if any, to bottom otherwise
* #param {int} [options.id] optional: the id of the message to scroll to
* #param {int} [options.offset] optional: the number of pixels to scroll
*/
scroll_to: function (options) {
window.alert("In function scroll_to");
options = options || {};
if (options.id !== undefined) {
var $target = this.$('.o_thread_message[data-message-id=' + options.id + ']');
if (options.only_if_necessary) {
var delta = $target.parent().height() - $target.height();
var offset = delta < 0 ? 0 : delta - ($target.offset().top - $target.offsetParent().offset().top);
offset = - Math.min(offset, 0);
this.$el.scrollTo("+=" + offset + "px", options);
} else if ($target.length) {
this.$el.scrollTo($target);
}
} else if (options.offset !== undefined) {
this.$el.scrollTop(options.offset);
} else {
window.alert("55555555555");
window.alert("55555555555" + this.el.scrollHeight);
//this.$el.scrollTop(this.el.scrollHeight);
this.$el.scrollTop(20);
}
},
get_scrolltop: function () {
return this.$el.scrollTop();
},
is_at_bottom: function () {
window.alert("777777777777777");
return this.el.scrollHeight - this.$el.scrollTop() - this.$el.outerHeight() < 5;
},
unselect: function () {
this.$('.o_thread_message').removeClass('o_thread_selected_message');
this.selected_id = null;
},
});
I've put some alertboxes to see what happens when the page is loaded.
It seems it goes straight to the part with "5555555".
I've tried some changes there to adjust the scrollbar but nothing happens.
Does anyone have an idea on how to get the scrollbar on top as default?
Hi: Last message on top you can see this page:
Change message order in discuss odoo 9
I have test it at Odoo10 And it run well:
display_order set as DESC
init: function (parent, options) {
this._super.apply(this, arguments);
this.options = _.defaults(options || {}, {
display_order: ORDER.DESC,
},
through an friend's Help,Now I'm OK
share the code :
scroll_to: function (options) {
options = options || {};
if (options.id !== undefined) {
var $target = this.$('.o_thread_message[data-message-id="' + options.id + '"]');
if (options.only_if_necessary) {
var delta = $target.parent().height() - $target.height();
var offset = delta < 0 ? 0 : delta - ($target.offset().top - $target.offsetParent().offset().top);
offset = - Math.min(offset, 0);
this.$el.scrollTo("+=" + offset + "px", options);
} else if ($target.length) {
this.$el.scrollTo($target);
}
} else if (options.offset !== undefined) {
this.$el.scrollTop(options.offset);
} else {
// this.$el.scrollTop(this.el.scrollHeight);
this.$el.scrollTop();
console.log("flag 4");
}
},

Open totally new window when clicking on screen

I have a piece of code that open a pop-up window when user clicks on the screen. The problem is, if you click again, it will not open another pop-up, it will just "reload" the already opened window. There is a way to create another with second click on screen?
Here is the code:
function makePopunder(pUrl) {
var _parent = (top != self && typeof (top["document"]["location"].toString()) === "string") ? top : self;
var mypopunder = null;
var pName = (Math["floor"]((Math["random"]() * 1000) + 1));
var pWidth = window["innerWidth"];
var pHeight = window["innerHeight"];
var pPosX = window["screenX"];
var pPosY = window["screenY"];
var pWait = 3600;
pWait = (pWait * 1000);
var pCap = 50000;
var todayPops = 0;
var cookie = "_.mypopunder";
var browser = function () {
var n = navigator["userAgent"]["toLowerCase"]();
var b = {
webkit: /webkit/ ["test"](n),
mozilla: (/mozilla/ ["test"](n)) && (!/(compatible|webkit)/ ["test"](n)),
chrome: /chrome/ ["test"](n),
msie: (/msie/ ["test"](n)) && (!/opera/ ["test"](n)),
firefox: /firefox/ ["test"](n),
safari: (/safari/ ["test"](n) && !(/chrome/ ["test"](n))),
opera: /opera/ ["test"](n)
};
b["version"] = (b["safari"]) ? (n["match"](/.+(?:ri)[\/: ]([\d.]+)/) || [])[1] : (n["match"](/.+(?:ox|me|ra|ie)[\/: ]([\d.]+)/) || [])[1];
return b;
}();
function isCapped() {
try {
todayPops = Math["floor"](document["cookie"]["split"](cookie + "Cap=")[1]["split"](";")[0]);
} catch (err) {};
return (pCap <= todayPops || document["cookie"]["indexOf"](cookie + "=") !== -1);
};
function doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
if (isCapped()) {
return;
};
var sOptions = "toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width=" + pWidth.toString() + ",height=" + pHeight.toString() + ",screenX=" + pPosX + ",screenY=" + pPosY;
document["onclick"] = function (e) {
if (isCapped() || window["pop_clicked"] == 1 || pop_isRightButtonClicked(e)) {
//return;
};
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
var now = new Date();
document["cookie"] = cookie + "=1;expires=" + new Date(now["setTime"](now["getTime"]() + pWait))["toGMTString"]() + ";path=/";
now = new Date();
document["cookie"] = cookie + "Cap=" + (todayPops + 1) + ";expires=" + new Date(now["setTime"](now["getTime"]() + (84600 * 1000)))["toGMTString"]() + ";path=/";
pop2under();
};
};
};
function pop2under() {
try {
mypopunder["blur"]();
mypopunder["opener"]["window"]["focus"]();
window["self"]["window"]["blur"]();
window["focus"]();
if (browser["firefox"]) {
openCloseWindow();
};
if (browser["webkit"]) {
openCloseTab();
};
} catch (e) {};
};
function openCloseWindow() {
var ghost = window["open"]("about:blank");
ghost["focus"]();
ghost["close"]();
};
function openCloseTab() {
var ghost = document["createElement"]("a");
ghost["href"] = "about:blank";
ghost["target"] = "PopHelper";
document["getElementsByTagName"]("body")[0]["appendChild"](ghost);
ghost["parentNode"]["removeChild"](ghost);
var clk = document["createEvent"]("MouseEvents");
clk["initMouseEvent"]("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
ghost["dispatchEvent"](clk);
window["open"]("about:blank", "PopHelper")["close"]();
};
function pop_isRightButtonClicked(e) {
var rightclick = false;
e = e || window["event"];
if (e["which"]) {
rightclick = (e["which"] == 3);
} else {
if (e["button"]) {
rightclick = (e["button"] == 2);
};
};
return rightclick;
};
if (isCapped()) {
return;
} else {
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);
};
}
makePopunder('http://www.stackoverflow.com');
You seem to run the 'open' command with the name attribute set. This creates a reference of that name to the window, when you then run that command again with the same window it will use the window that already has that reference. The solution would be to run open without name:
open(url, '', ...)
Here is some documentation on open

Javascript pop under window (Background window)

I'm to open pop-up windows BEHIND the current active screen using java script.
Here is my simple code.
var win = window.open('http://yahoo.com',null,"height=400,width=600,status=yes,toolbar=no,scrollbars=yes,menubar=yes,location=yes");
win.blur();
this.window.focus();
But it doesn't seems to be work in any browser. It simply opens a pop up.I referred this question from stackoverflow. But it doesn't work. My aim is to create a background window in all browsers. Someone help me please
You cannot do this. Modern web browsers do not allow websites to steal the focus from other tabs (because this could become quite messy for the users). The only thing that you could do is prompt your users to open in a new tab (which does not change the focus). Or you can abuse an alert to get the focus back to your page:
var win = window.open('http://yahoo.com',null,"target=_blank,height=400,width=600,status=yes,toolbar=no,scrollbars=yes,menubar=yes,location=yes");
alert("Welcome back");
function makePopunder(pUrl) {
var _parent = (top != self && typeof (top["document"]["location"].toString()) === "string") ? top : self;
var mypopunder = null;
var pName = (Math["floor"]((Math["random"]() * 1000) + 1));
var pWidth = window["innerWidth"];
var pHeight = window["innerHeight"];
var pPosX = window["screenX"];
var pPosY = window["screenY"];
var pWait = 3600;
pWait = (pWait * 1000);
var pCap = 50000;
var todayPops = 0;
var cookie = "_.mypopunder";
var browser = function () {
var n = navigator["userAgent"]["toLowerCase"]();
var b = {
webkit: /webkit/ ["test"](n),
mozilla: (/mozilla/ ["test"](n)) && (!/(compatible|webkit)/ ["test"](n)),
chrome: /chrome/ ["test"](n),
msie: (/msie/ ["test"](n)) && (!/opera/ ["test"](n)),
firefox: /firefox/ ["test"](n),
safari: (/safari/ ["test"](n) && !(/chrome/ ["test"](n))),
opera: /opera/ ["test"](n)
};
b["version"] = (b["safari"]) ? (n["match"](/.+(?:ri)[\\/: ]([\\d.]+)/) || [])[1] : (n["match"](/.+(?:ox|me|ra|ie)[\\/: ]([\\d.]+)/) || [])[1];
return b;
}();
function isCapped() {
try {
todayPops = Math["floor"](document["cookie"]["split"](cookie + "Cap=")[1]["split"](";")[0]);
} catch (err) {};
return (pCap <= todayPops || document["cookie"]["indexOf"](cookie + "=") !== -1);
};
function doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
if (isCapped()) {
return;
};
var sOptions = "toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width=" + pWidth.toString() + ",height=" + pHeight.toString() + ",screenX=" + pPosX + ",screenY=" + pPosY;
document["onclick"] = function (e) {
if (isCapped() || window["pop_clicked"] == 1 || pop_isRightButtonClicked(e)) {
//return;
};
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
var now = new Date();
document["cookie"] = cookie + "=1;expires=" + new Date(now["setTime"](now["getTime"]() + pWait))["toGMTString"]() + ";path=/";
now = new Date();
document["cookie"] = cookie + "Cap=" + (todayPops + 1) + ";expires=" + new Date(now["setTime"](now["getTime"]() + (84600 * 1000)))["toGMTString"]() + ";path=/";
pop2under();
};
};
};
function pop2under() {
try {
mypopunder["blur"]();
mypopunder["opener"]["window"]["focus"]();
window["self"]["window"]["blur"]();
window["focus"]();
if (browser["firefox"]) {
openCloseWindow();
};
if (browser["webkit"]) {
openCloseTab();
};
} catch (e) {};
};
function openCloseWindow() {
var ghost = window["open"]("about:blank");
ghost["focus"]();
ghost["close"]();
};
function openCloseTab() {
var ghost = document["createElement"]("a");
ghost["href"] = "about:blank";
ghost["target"] = "PopHelper";
document["getElementsByTagName"]("body")[0]["appendChild"](ghost);
ghost["parentNode"]["removeChild"](ghost);
var clk = document["createEvent"]("MouseEvents");
clk["initMouseEvent"]("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
ghost["dispatchEvent"](clk);
window["open"]("about:blank", "PopHelper")["close"]();
};
function pop_isRightButtonClicked(e) {
var rightclick = false;
e = e || window["event"];
if (e["which"]) {
rightclick = (e["which"] == 3);
} else {
if (e["button"]) {
rightclick = (e["button"] == 2);
};
};
return rightclick;
};
if (isCapped()) {
return;
} else {
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);
};
}
makePopunder("http://www.yourdomain.com/");

Magento - this javascript file doesn't merge correctly

i have a magento 1.6.2 webshop.
I would like to merge the javascript files for optimizing my loadingspeeds.
But when i select merge in the settings my Custom Menu extensions doesn't work anymore.
I guess there is something wrong in the code.
I have tried to contact the developer, but i don't get a reaction ...
This extension is for the navigation menu at the top (with images)
Here is the code of the custommenu.js file:
function wpShowMenuPopup(objMenu, popupId)
{
objMenu = $(objMenu.id); var popup = $(popupId); if (!popup) return;
popup.style.display = 'block';
objMenu.addClassName('active');
var popupWidth = CUSTOMMENU_POPUP_WIDTH;
if (!popupWidth) popupWidth = popup.getWidth();
var pos = wpPopupPos(objMenu, popupWidth);
popup.style.top = pos.top + 'px';
popup.style.left = pos.left + 'px';
if (CUSTOMMENU_POPUP_WIDTH) popup.style.width = CUSTOMMENU_POPUP_WIDTH + 'px';
}
function wpPopupPos(objMenu, w)
{
var pos = objMenu.cumulativeOffset();
var wraper = $('custommenu');
var posWraper = wraper.cumulativeOffset();
var wWraper = wraper.getWidth() - CUSTOMMENU_POPUP_RIGHT_OFFSET_MIN;
var xTop = pos.top - posWraper.top + CUSTOMMENU_POPUP_TOP_OFFSET;
var xLeft = pos.left - posWraper.left;
if ((xLeft + w) > wWraper) xLeft = wWraper - w;
return {'top': xTop, 'left': xLeft};
}
function wpHideMenuPopup(element, event, popupId, menuId)
{
element = $(element.id); var popup = $(popupId); if (!popup) return;
var current_mouse_target = null;
if (event.toElement)
{
current_mouse_target = event.toElement;
}
else if (event.relatedTarget)
{
current_mouse_target = event.relatedTarget;
}
if (!wpIsChildOf(element, current_mouse_target) && element != current_mouse_target)
{
if (!wpIsChildOf(popup, current_mouse_target) && popup != current_mouse_target)
{
popup.style.display = 'none';
$(menuId).removeClassName('active');
}
}
}
function wpIsChildOf(parent, child)
{
if (child != null)
{
while (child.parentNode)
{
if ((child = child.parentNode) == parent)
{
return true;
}
}
}
return false;
}
You can see it working on my webshop: www.liefstoereigenwijs.nl
Can anyone see if there is something wrong in the code?
Or has a other solution for my problem?
problem is automatically solved in 1.7.0.2
End each
function xx(x)
{
...
}
with a ; at the end!
So:
function xx(x)
{
...
};

Categories