How do I when the user clicks anywhere on my website to open a certain external site in a new tab and with cookies to limit the opening of the site determined by time?
How do I when the user clicks anywhere on my website to open a certain external site in a new tab and with cookies to limit the opening of the site determined by time?
In summary this would be:
<script>
(function () {
var isOpened = false;
//Troque aqui pelo site desejado
var siteUrl = "http://www.google.com.br";
document.addEventListener("click", function(){
if (!isOpened) {
isOpened = !!window.open(siteUrl, "_blank");
}
});
})();
</script>
Add the click event to document.
, use window.open
without window configuration parameters, create a isOpened
variable to check if the popup has already been opened, has been clicked then ignores the next clicks ( also you can use document.removeEventListener
)
Note [1] : I've added
!!
in front ofwindow.open
because some popup blocking plugins block even calls from clicks,window.open
returnsnull
, so you'll know if the popup was opened or not.Note [2] : I used an anonymous function to isolate variables from the global scope, thus avoiding crashes.
The AP asked me for extra functionality, I'm separated from the above context because the above code I believe will help people in specific situations, in this case the AP wants to limit a click every 24 hours, that is, it opened the popup once only in 24 hours will it occur again, even if you refresh the page.
This can be solved using cookies, for example:
<script>
//Função pra verificar se a janela foi já aberta hoje
function checkOpenPopupToday()
{
return /(^|;\s)isopenedpopup=1(;|$)/.test(document.cookie);
}
//Função pra definir em horas que a janela foi aberta
function setOpenPopupToday(hours)
{
var date = new Date();
date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
document.cookie = "isopenedpopup=1; expires=" + date.toGMTString() + "; path=/";
}
(function () {
//Troque aqui pelo site desejado
var siteUrl = "http://www.google.com.br";
//Troque aqui pelo tempo em horas desejado para impedir que o popup abra neste intervalo
var hours = 24;
document.addEventListener("click", function()
{
//Verificar pelo cookie
if (!checkOpenPopupToday())
{
//Verificar se o popup abriu com o clique
if (!!window.open(siteUrl, "_blank"))
{
//Se a janela foi aberta define o tempo para bloquear novas aberturas
setOpenPopupToday(hours);
}
}
});
})();
</script>