How to create a Magento 2 Modal popup that cannot be closed?
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"));
}
);
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.