3

I need to make a link to open a page and add some scripts into it.

That's why i thought creating bookmarklet is the best way. For example, i want to redirect user to a page and alert user when he/she tries to close the tab.

The code i want to use

javascript:(function(){ 
   window.location.replace("https://google.com");
   window.onbeforeunload = function (e) {
   e = e || window.event;

   // For IE and Firefox prior to version 4
   if (e) {
       e.returnValue = 'Sure?';
   }

   // For Safari
   return 'Sure?';
   };
})();

I created anchor like:

<a href="javascript:(function(){window.location.replace("https://google.com"),window.onbeforeunload=function(e){return(e=e||window.event)&&(e.returnValue="Sure?"),"Sure?"};})();">Click</a>

Is it possible to do that? And what is wrong with the js code cause it doesnt works ?

Can
  • 659
  • 1
  • 7
  • 24

1 Answers1

1

Unfortunately, this cannot be done. When you click on a page, the bookmarklet's JS runs on that page. Even if the JS opens another page, due to how browsers handle JS and security, there's no was that the same JS can continue to run on the second page, or control anything on it.

What you need here is a userscript. Tampermonkey and similar extensions allow you to run scripts which can modify content and run on different pages.

undo
  • 257
  • 3
  • 19