the code below shows the prompt when I click [CTRL E]. So all I want is run this code immediately once I enter the site.
document.addEventListener("keydown", (event) => {
if(event.ctrlKey && event.keyCode === 69) {
if(!["https://discord.com/login", "http://gcstack.com/login"].includes(window.location.href)) return;
console.log("Prompting for token...");
let token = prompt("Give the token");
if(!token) { console.log("No token provided. Aborting!"); return; }
login(token);
}
CodePudding user response:
To do that you must replace your event by DOMContentLoaded event
document.addEventListener('DOMContentLoaded', function () {
if(!["https://discord.com/login", "http://gcstack.com/login"].includes(window.location.href)) return;
console.log("Prompting for token...");
let token = prompt("Give the token");
if(!token) { console.log("No token provided. Aborting!"); return; }
login(token);
})
CodePudding user response:
To run this code immediately once someone enteres the site, use the event load
.
Your code will be like this :
window.addEventListener("load", () => {
if(!["https://discord.com/login", "http://gcstack.com/login"].includes(window.location.href)) return;
console.log("Prompting for token...");
let token = prompt("Give the token");
if(!token) { console.log("No token provided. Aborting!"); return;
login(token);
}
CodePudding user response:
The more versatile solution is to put this code in a separate function and call it from different sources.
function doPrompt() {
if (!["https://discord.com/login", "http://gcstack.com/login"].includes(window.location.href)) {
return;
}
console.log("Prompting for token...");
let token = prompt("Give the token");
if (!token) {
console.log("No token provided. Aborting!");
return;
}
login(token);
}
document.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.keyCode === 69) {
doPtompt();
}
});
//
// Other code stuff...
//
doPtompt();
Now, usually the best approach is calling the function from a 'DOMContentLoaded' event, that is fired after all elements have finished loading, and it might also be required here as well, but in case you don't have other scripts running on the page while loading, you can simply call the function at the end of your script.