Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent the browser from loading a web app in vanilla JavaScript?

I wrote the following Greasemonkey script to prevent myself from accessing a few web apps (web sites), usually these I feel a bit addicted to. This is the closest I got to prevent my Browsers to display these sites:

// ==UserScript==
// @name        blocko
// @include     *
// ==/UserScript==

window.addEventListener('load', function() {
    let sites = ['example-1.com', 'example-2.com', 'example-3.com'];
    let dotTLD_andAllAfterIt = /\..+/;
    let href = window.location.href;
    for (let i = 0; i < sites.length; i++) {
        if (href.includes(sites[i])) {
            let domain = sites[i].replace(dotTLD_andAllAfterIt, '');
            document.body.innerHTML =`
                <div style="direction: ltr; position: fixed; top: 0; z-index: 999999; display: block; width: 100%; height: 100%; background: red">
                  <p style="position: relative; top: 40%; display: block; font-size: 66px; font-weight: bold; color: #fff; margin: 0 auto; text-align: center">
                    Enough with this ${domain} bullshit!
                  </p>
                </div>
          `;
        }
    }
}, true);

I'm not satisfied of my achievement here as this script gets me into the site and I need to wait 1/2/3/4 or even 5 or more seconds in rare cases, until the site will vanish and the message I print to the screen with red background will appear instead. Thus I'm unwillingly exposed to the site's content, from which I want to avoid.

I desire to prevent the browser from even navigating into a website, through JavaScript. There is a Chrome addon named "BlockSite" that helps with this and I tried to examine its (huge) source code but failed to understand how it prevents the user to be moved into a website, unlike my script above that moves the user to the website but vanishes the website with a message after a few seconds (after the load event was triggered).

Please share a way to totally prevent yourself of moving into a website, as with "BlockSite".

like image 750
user9303970 Avatar asked Mar 10 '18 11:03

user9303970


3 Answers

You need to wait so long as you are using a window load Event. You need to use DOMContentLoaded event instead. The difference is explained here on this answer.

It will work much faster if you change

window.addEventListener('load', function() {
   //Your Code
}, true);

To

document.addEventListener("DOMContentLoaded", function(event) {
   //Your Code
});

Lots of free extensions are available to block unwanted domains. Let me know if you want to build one for chrome, in that case I can further assist.

Update: Deleted following paragraph based on comments

But if you want to make your own extention then you need to be browser specific. As you need to write different extensions for different browsers.

like image 87
Munim Munna Avatar answered Sep 28 '22 01:09

Munim Munna


As a solution you can override onclick method of all links in your website. Then decide to let a user to follow the link or not.

const blackList = [`example-1.com`, `example-2.com`]

function onClick(event) {
  const href = this.href.match(/^(?:https?:)?(?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/i)
  if (!href) return
  const domain = href[1]
  if (blackList.includes(domain)) {
    event.stopPropagation()
    event.preventDefault()
    document.body.innerHTML =`
      <p>
        Enough with this ${domain} bullshit!
      </p>
    `;
  }
}

const elements = document.getElementsByTagName(`a`);
for(let element of elements) {
  element.onclick = onClick
}

.: UPDATE :.

Ok, let me explain the code above.

The code adds click listener to all links (<a href="...">...</a>) of your current page. When a user clicks the function above would be triggered.

const href = this.href.match - we extract from the href only domain part in order to compare does the url exist in our blackList or not -> if (blackList.includes(domain)).

this - refers to the link property href for more info check this article.

Here is a demo and here is the source code.

like image 24
sultan Avatar answered Sep 27 '22 23:09

sultan


  • Try this if want to stop: window.stop documentation (cannot stop the document in which it is contained from loading)
  • Try this if you want to prevent page reload/redirect link: onbeforeunload documentation (don't prevent loading automatically but allow a user to choose to follow the link or not)

    window.onbeforeunload = function(e) {
    
      var dialogText = 'Are you sure?';
    
       e.returnValue = dialogText;
    
       return dialogText;
    
    };
    
like image 44
Alex Nikulin Avatar answered Sep 27 '22 23:09

Alex Nikulin