This question already has answers here:
JavaScript: Overriding alert()
(12 answers)
Closed 2 years ago.
I have many JavaScript functions for a program, all of which contain alerts notifying the user of certain things. I wanted to give the user the option to ban all of those alerts, without having to rewrite all of the functions without the alerts. Is there a way to ban alert? Maybe something like this:
<button onclick = "alertBan()">Alert Ban</button>
function alertBan(){
alerts = false;
}
Just assign an empty function to alert.
function alertBan(){
alert = function(){};
}
If you might need to reenable alerts later on, you can store window.alert in a variable when the page loads.
const oldAlert = alert;
function alertBan(){
alert = function(){};
}
function enableAlerts(){
alert = oldAlert;
}
Store the original alert for perhaps later use. Replace the alert through empty function or with setted parameter to write on console.
If need the normal alert back take the stored one back.
alertOrig = alert;
function alertBan(consoleLog){
alert = function(e) {
if (consoleLog) console.log(e);
}
}
function alertEnable(){
if ( alertOrig )
alert=alertOrig;
}
alertBan();
alert('No console + no alert');
alertBan(true);
alert('With console');
alertEnable();
alert('Normal alert');
Related
This question already has an answer here:
Show warning message before close window in Java Script
(1 answer)
Closed 3 years ago.
I want to alert users before leaving the page - if button bsave is visible - that changes are not saved.
Nothing works (Chrome, other browsers are not tested).
$(window).on('beforeunload', function(){
if($('#bsave').is(':visible')){
alert('CHANGES ARE NOT SAVED !');
return; // should prevent closing the window
}
});
Also tried the following - without success
$(window).on('beforeunload', function(){
var c=confirm();
if(c){
return true;
}
else
return false;
Any help?
Instead using alert method, just return your message. Browsers will automatically create an alert for that:
window.onbeforeunload = function() {
if ($('#bsave').is(':visible')){
return 'CHANGES ARE NOT SAVED !';
}
}
According to the docs:
To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.
The beforeunload function should return a string if you want it to provide a response to the user if they're leaving a page:
$(window).on('beforeunload', function(){
if($('#bsave').is(':visible')){
return 'CHANGES ARE NOT SAVED !'; // should prevent closing the window
}
});
you need to add paranthese only, it is working properly.
$(window).on('beforeunload', function(){
var c=confirm();
if(c){
return true;
}
else
return false;
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a basic function in JavaScript that simply takes some pre-set values and puts them onto the screen by the use of a pre-made function. When I breakpoint the first line of what it is I'm doing, the page loads fine, as expected, but as soon as I remove that breakpoint, none of the information is set. and the page is blank.
this.QuizSelection = function () {
// Fill the ID's with the right info
app.SetBackground('head', this.HeroImage);
console.log('1 ' + this.HeroImage);
app.LoadInnerHTML('breadcrumbs', 'Home / ' + this.Title);
app.LoadInnerHTML('quizSelectionTitle',this.Title);
console.log('2 ' + this.Title);
app.LoadInnerHTML('quizSelectionIntro',this.Introduction);
console.log('3 ' + this.Introduction);
// Show the Quiz Selection and Heading
app.ShowSection('head');
app.ShowSection('quizSelection');
console.log('Quiz Selection');
}.bind(this);
The functions inside that (SetBackground and LoadInnerHTML) are just small one line functions that change the inner html and the set a background image.
// Change Inner HTML
this.LoadInnerHTML = function (id, html) {
var d = document.getElementById(id);
d.innerHTML = html;
}
// Set Background Image
this.SetBackground = function (id, image) {
document.getElementById(id).style.backgroundImage = 'url(image)';
}
I can't understand why it wouldn't work when the breakpoint isn't on. Clearly it does work, because everything is fine with the breakpoint on, but then when it's off the result I get output to the console is:
1
2
3 undefined
Quiz Selection
You have a race condition.
The act of hitting a breakpoint makes your code wait for the async JSON load to complete. Without the breakpoint, the code trying to read the JSON is executing before the JSON has actually loaded.
See How do I return the response from an asynchronous call? for how to fix this issue.
You have console.log statements in your code. When the debugger is not on, console object does not exist (this is true for IE not for Chrome to the best of my knowledge), thus your javascript code execution fails.
If I have a page overriding window.alert box:
Window.alert = function() {}
can I re-enable the alert box if I have access to the Javascript?
I guess I would save the original alert function off somewhere else and then reassign it back to it.
var originalAlert = window.alert;
window.alert = function(stuff) {
console.log('alert invoked');
}
alert(); // displays a message in the console
var newWindow = window.open();
window.alert = newWindow.alert;
newWindow.close();
alert(); // alerts a message
I don't know that I would open a new window just to get the alert function, but that function is native code, so once it's been closed over, you can't get it back without some crazy hack like this. At least not that I'm aware of.
This question already has answers here:
chrome.storage.local.get and set [duplicate]
(3 answers)
Closed 8 years ago.
I have a chrome extension that is using storage and I can't get the value from the storage with one enter click.
There is a single input field. After the user enters a value and presses enter, the extension should take the value from storage and add the user's input to this value. The first enter press it doesn't work, but if user clicks Enter for second time, then stored value is seen.
I assume that problem is in the ordering of functions, but I can't understand where exactly.
Code in correct order:
var repo, moduleCodes, url;
// Third process
function getStoredUrl() {
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
});
}
// Fourth process
function setVariables() {
repo = document.getElementById("repo").value.toLowerCase();
moduleCodes = {
admin: "EHEALTHADM"
};
}
// Second process
function openGraph() {
getStoredUrl();
setVariables();
if (moduleCodes[repo] !== undefined) {
// ERROR: field "test" doesn't have value url, but should to have
document.getElementById("test").value = url;
//window.open(url + moduleCodes[repo]);
} else {
returnError("Can't find repo " + repo, "repo");
}
}
var enter = 13;
// First process
function inputRepoListener(e) {
"use strict";
if (e.keyCode === enter) {
openGraph();
}
}
The whole code can be seen on gitHub repo: https://github.com/iriiiina/fisheyeGraph
This is a typical race condition, caused by asynchronous method calls.
The call to storage.sync.get is asynchronous, i.e. the normal program flow continues while the storage values are being retrieved. This means that also the assignment of the (still empty) url variable to the element with id test happens before the storage value retrieval has finished.
Solution: Move everything that should happen after the storage value has been retrieved into the callback of storage.sync.get. If, for example, you assign the url like that, it will work.
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
document.getElementById("test").value = url;
});
So you need to restructure your code in order to meet this criteria.
I want to insert my debugger function inside another JS function and halt the execution.
I know return false/true does the job, but I want my debugger function to do that automatically.
Example:
<script type="javascript">
function validateFirstName () {
//validating first name field
var fn = $('#firstname').val();
if(fn == "") {
$("#errorMsg").html("Please insert first name");
$("#firstname").focus();
return false;
}
debugger(); //I want to stop everything here
// if validation passes, redirect browser:
window.location = 'nextpage.html';
}
function debugger () {
console.log("Some custom message here");
return false;
}
</script>
You'll notice I put my debugger function inside the validateFirstName() function.
I assumed that return false in my debugger() function will stop the validateFirstName() from executing. But it doesn't.
Without adding return false inside the validateFirstName() function, how can I use my debugger() function to stop all execution?
replace
debugger(); //I want to stop everything here
with
return debugger(); //I want to stop everything here
the above example will always stop on true or false.
This will continue to the window.location if it's true and stop if it's false.
if(!debugger())
return;
in your case it seems to be a function inside of a function so you might as well use
if(!debugger())
return false;
Seems what you really want to do is set a breakpoint on the executing code.
In Chrome Browser press Ctrl+Shift+I
Then Go to Sources Tab
Click the Arrow pointing right (looks like a play button) on top of the counting line numbers to see list of websites
Find your website click on the folder
Find whatever script that you want
Now click anywhere in the code to close the side bar
Now finally click on any number on the side thats counting down the lines
That will set a breakpoint which means it will stop on that code if you make the code go there by doing something on your website, or forcing the code to run using the
Console tab or simply in your address bar typing javascript: function_to_call();
You could throw from debugger () like this.
function debugger () {
console.log('Some custom message here');
throw 'Debugging Code';
}
Although this will do what you want it to, I don't recommend it. Basically what's happening is you are throwing an error which isn't being caught in your code (the browser will catch it, but that is probably not as clean).
You could throw an error:
function validateFirstName () {
//validating first name field
var fn = $('#firstname').val();
if(fn==""){
$("#errorMsg").html("Please insert first name");
$("#firstname").focus();
return false;
}
debugger(); //I want to stop everything here
// if validation passes, redirect browser:
window.location='nextpage.html';
}
function debugger () {
throw new Error("Some custom message here");
}
try{
validateFirstName();
}catch(e){
console.log(e);
}
If you are using a modern browser like Chrome, why not just use debugger instead?
that will trigger the debugger in your developer tools.
like this:
debugger; //I want to stop everything here
notice the missing ()