I have a user-config page in my settings page and the user-config page is opened by JS
<a onclick="window.open("@/@user-config.php", "User Config", "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=350,height=450");">Open User Config Window</a>
It should not be opened directly,
So, Is there a way to detect whether the window is opened by JS or Not
Thanks 😐
For me, the best thing would be to allow the page to be opened directly. Users will do what users do.
But if you don't want to do that (or can't for some reason), the first thing that comes to mind is to have the JavaScript open a window without a URL (for instance, about:blank) and then populate that window with the result of doing an ajax call with a header that won't be set on a direct request (unless someone does a direct request with Postman or something, and worrying about that is probably overkill). The PHP can check for the header. That looks something like this:
function openUserConfig() {
const win = window.open("about:blank", "User Config", "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=350,height=450");
win.document.write("<em>Loading...</em>");
win.document.close();
fetch("@/@user-config.php", {
headers: {
"The-Header": "Header Value",
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.text();
})
.then(html => {
win.document.write(html);
win.document.close();
})
.catch(() => {
win.document.write("<strong>Error loading user config</strong>"); // Or whatever
win.document.close();
});
}
Combined with the PHP to check for the header and send back (for instance) a 403 response if it's not there.
Note that the document markup returned by @/@user-config.php will also need a base element so that relative URLs in the page (for CSS, JavaScript, fonts; links in the text) resolve correctly. (Or make all the URLs in the page absolute, or inline everything.)
But again, I'd go with making it something you can directly open if possible.