0

I am working on a project where I need to block some websites, so my approach is - whenever a person enters a URL of a specific website; it automatically redirects to another page.. for example: if a person clicks a link to enter into google.com, the browser automatically sends that person to stackoverflow.com.

here is my javascript code:

    function fun(){
    d=window.location.href

    if (d=='https://www.google.com/') {
    window.location.replace('https://stackoverflow.com/');
    } else {
        window.open(d);
    }
     }

I know it's not a good method to block a website, but IDK why my code does not work.. it would be better if suggest how website blocking actually works

Anonymous
  • 835
  • 1
  • 5
  • 21
  • Is this code executing in a browser extension or just a normal html file? – Anonymous Jul 27 '22 at 05:00
  • well i want to convert this code into an extension, but for testing and learning purpose i am doing in HTML file –  Jul 27 '22 at 05:02
  • 1
    `window.location.href` returns the url of the current page, so the value of `d` would always be your current file url, like `C:/Users/admin/Desktop/urlblocker.html` If you are doing it in a separate HTML file then you would need to execute this on google.com i.e. the website you are trying to block Instead, you can create an extension that runs on all websites the user visits – Anonymous Jul 27 '22 at 05:03
  • I have converted everything into an extension, but when i run the above code in ***google.com*** or any other website; it doesnot actually work.. So,i tried printing the URL in console so that i can get what the error is ... I found that when i run- **d=window.location.href; console.log(d);** it returns the adress of the page where extension is stored i.e, ***"chrome-extension://poklpbbddeimdmkjbojljhhnhignpmfl/popup.html"*** idk why this extension is showing its own adress instead of the page where i run it.. –  Jul 28 '22 at 19:00
  • 1
    Great! Now you can look into the [documentation](https://developer.chrome.com/docs/extensions/) as to how to do stuff with your extension, for your case you can look into [this question](https://stackoverflow.com/questions/73164475/how-to-detect-if-a-url-is-opened-in-a-chrome-extension), or you can also look into the tag [google-chrome-extension] – Anonymous Jul 29 '22 at 10:51

0 Answers0