How to create a Magento 2 Modal popup that cannot be closed?
-
04-10-2020 - |
Question
I'm trying to create a modal popup that cannot be closed. It has a button that takes you to the next page by clicking on it, but I don't want users to be able to close it.
The modal popup can be closed in 3 ways:
- Clicking the cross/
[X]
button in the top right corner - Pressing escape
- Click on the overlay
So far this is my modal JS and I think with clickableOverlay: false
I've already tackled the 3rd one:
require(
[ 'jquery', 'Magento_Ui/js/modal/modal' ],
function($, modal) {
$("#popup").modal({
autoOpen: true,
responsive: true,
clickableOverlay: false,
modalClass: 'modal-custom',
title: 'Popup',
buttons: [{
text: $.mage.__('Take me back to the homepage'),
class: 'action close-popup wide',
click: function () {
window.location.href = '/';
}
}]
});
}
);
UPDATE:
I also tried to setup the modal in a different way when trying the provided solutions:
require(
[ 'jquery', 'Magento_Ui/js/modal/modal' ],
function($, modal) {
modal({
//options
}, $("#popup"));
}
);
Solution
I couldn't get an override of the modal.closeModal()
function to work via mixins and also I think doing it via a mixin makes it override through the whole website on all modals, which I do not want. I only need it on this one modal.
I ended up by simply removing any trigger that will call modal.closeModal()
. There are some other modal options you can use to achieve that:
- I hide the close button on opening the modal with the
opened
option/event which will be triggered right after the modal has been opened - I'm overriding the
keyEventHandlers.escapeKey
option
So this is my final code:
require(
[ 'jquery', 'Magento_Ui/js/modal/modal' ],
function($, modal) {
modal({
autoOpen: true,
responsive: true,
clickableOverlay: false,
modalClass: 'modal-custom',
title: 'Popup',
buttons: [{
text: $.mage.__('Take me back to the homepage'),
class: 'action close-popup wide',
click: function () {
window.location.href = '/';
}
}],
opened: function($Event) {
$('.modal-header button.action-close', $Event.srcElement).hide();
},
keyEventHandlers: {
escapeKey: function () { return; }
}
}, $("#popup"));
}
);
OTHER TIPS
I reckon using mixins in that case would be relevant.
You can try the following:
First in your module, create the following view/base/requirejs-config.js
:
var config = {
'config':{
'mixins': {
'Magento_Ui/js/modal/modal': {
'Vendor_Module/hook':true
}
}
}
};
Then create view/base/web/hook.js
:
define([], function(){
'use strict';
return function(targetModule){
targetModule.closeModal = function(){
return false;
}
return targetModule;
};
});
With this mixin, you replace the implementation of the closeModal
method with your own method. In that case, returning false would avoid closing the modal.
Side note: I hate you for doing this. Unclosable popups should be banned from the web.