Home > Back-end >  close a window if open by url
close a window if open by url

Time:02-05

hey guys I was making a site that uses a password and redirects you to another site but you can just look up the url for the secondary site. I was wondering if theirs a way to make it close if forced open by a url

CodePudding user response:

To close a window that was opened via JavaScript, first you need to store it in a variable:

var w = window.open("https://majorflux.codehs.me");

Then you can use the window.close method:

w.close();

You can store windows in objects to allow you to use the URL of the window to access it:

var windows = {};

function newWindow(url){
    windows[url] = window.open(url);
    console.log("The window with the url \u0022"   url   "\u0022 was opened");
}
function closeWindow(url){
    windows[url].close();
    console.log("The window with the url \u0022"   url   "\u0022 was closed")
}
function getWindow(url){
    return(windows[url] || "404 not found");
}
function getDocument(url){
    return(windows[url].document || "404 not found");
}

Please let me know if this wasn't the answer you were looking for.

CodePudding user response:

I think that what you want is to protect your routes, rather than close them. If you want to search efficiently for this matter, look up for 'How to protect routes?' and 'What is authorization and authentication?'.

I guess that you are working with an API, so what you could do is to create a function on client-side that runs before anything else does (if you are working with plain html and vanilla js, just put the script tag inside head). That function is meant to fetch your API route that handles authorization, then based off the response of that fetch call, you can redirect to the homepage or grant access to your protected route.

This is a very brief explanation, but this involves HTTP requests, asynch js and handling of promises, APIs routes, authorization and authentication methods. You should check all that out if those concepts are all new to you, and don't get discouraged, it may sound like a lot but it truly isn't.

  •  Tags:  
  • Related