95 lines
2.5 KiB
JavaScript
95 lines
2.5 KiB
JavaScript
/**
|
|
* first-time.js by Nick "Nycki" Lamicela, 2025.
|
|
*
|
|
* A simple script for redirecting the user to a "first time here" page, for example, a nsfw content opt-in page.
|
|
*
|
|
* You may use this on your site, with or without attribution.
|
|
*/
|
|
|
|
const firstTime = {};
|
|
|
|
/**
|
|
* Check if the user has opted into this gate. If not, redirect to gate page.
|
|
*
|
|
* Usage: in the head of each protected page.
|
|
*
|
|
* <head>
|
|
* <script src="/firstTime.js"></script>
|
|
* <script>firstTime.check("consent");</script>
|
|
* </head>
|
|
*/
|
|
|
|
firstTime.check = function (key='default', href=`/first-time-${key}/`) {
|
|
const currentSetting = localStorage.getItem(`first-time-${key}`);
|
|
if (currentSetting === 'granted') {
|
|
// do nothing
|
|
return;
|
|
} else {
|
|
// redirect to gate
|
|
const nextPage = window.location;
|
|
window.location.replace(`${href}?next=${nextPage}`);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Grant the user access to this gate.
|
|
*
|
|
* Usage: on the gate page.
|
|
*
|
|
* <head>
|
|
* <script src="/firstTime.js"></script>
|
|
* </head>
|
|
* <body>
|
|
* <button onclick="firstTime.grant('consent')">I Consent</button>
|
|
* </body>
|
|
*/
|
|
firstTime.grant = function (key='default') {
|
|
// save preference
|
|
localStorage.setItem(`first-time-${key}`, 'granted');
|
|
|
|
// redirect back to original page
|
|
let nextPage = '/';
|
|
const queries = (window.location.search || '').slice(1).split('&');
|
|
for (const query of queries) {
|
|
const [k, v] = query.split('=', 2);
|
|
if (k == 'next') {
|
|
nextPage = v;
|
|
}
|
|
}
|
|
window.location.replace(nextPage);
|
|
};
|
|
|
|
/**
|
|
* "No thanks" button for leaving a gate.
|
|
*
|
|
* Optional: on the gate page, after the consent button.
|
|
*
|
|
* <head>
|
|
* <script src="/firstTime.js"></script>
|
|
* </head>
|
|
* <body>
|
|
* <button onclick="firstTime.grant('consent')">I Consent</button>
|
|
* <button onclick="firstTime.leave('/index.html')">No Thanks</button>
|
|
* </body>
|
|
*/
|
|
firstTime.leave = function (href='/') {
|
|
window.location.replace(href);
|
|
};
|
|
|
|
/**
|
|
* "Clear settings" button for resetting a gate.
|
|
*
|
|
* Optional: on the gate page.
|
|
*
|
|
* <head>
|
|
* <script src="/firstTime.js"></script>
|
|
* </head>
|
|
* <body>
|
|
* <button onclick="firstTime.grant('consent')">I Consent</button>
|
|
* <button onclick="firstTime.leave()">No Thanks</button>
|
|
* <button onclick="firstTime.clear('consent'); firstTime.leave()">Clear this setting.</button>
|
|
* </body>
|
|
*/
|
|
firstTime.clear = function (key='default') {
|
|
localStorage.removeItem(`first-time-${key}`);
|
|
};
|