Skip to content

how to detect window.open

I am trying to solve a scenario and let me try to explain using an example. I have a script which tries to open a new url using window.open method. This script triggers a window open after 5 sec without any click event from the user. What I would like to do is .. capture the window open method. Is there any function available like addEventListener to capture window open method? I would like to track a window.open which was not initiated by user action.

Thanks Lynn

setTimeout(function(){
window.open(url,name);
}, 5000); 

Answer

You can replace it

NOTE: window.open does not work at stackoverflow due to sandboxing Also a window.open not triggered by a user action will likely be suppressed by the browser

const saveOpen = window.open;
window.open = function(url,windowName,parms) {
  console.log("triggered",url);
  saveOpen(url, windowName || "",parms || "")
};
const url = "https://stackoverflow.com", windowName="myWin"
setTimeout(function(){
  window.open(url,windowName);
}, 1000); 

As mentioned in How to call a function of another window in javascript? you could attach a load event listener to the window:

const loaded = function(str) { console.log(str) },
url = "https://stackoverflow.com", windowName="myWin";
setTimeout(function(){
  const w = window.open(url,windowName);
  if (w) w.addEventListener('load',function() { loaded(url)})
  else console.log('sorry, not allowed'); // this of course can be a call to whatever
}, 1000);