So im trying to replicate the window.confirm() prompt in javascript. here is the structure of what i tried.
function foo(){
if(customConfirm("Click yes or no"))
alert("Clicked yes");
else
alert("Clicked no");
}
function customConfirm(message){
$('#customConfirm').load("customAlert.html");
$('#okButton').click(function(e){
ret = true;
})
$('#cancelButton').click(function(e){
ret = false;
})
return ret;
}
If you're using raw JS, or at most JQuery instead of say React, Vue, etc., I would provide callbacks for the "customConfirm" so that say when you detect a button press on Ok and Cancel, and call each callback accordingly. This would require the use of event handlers which is fairly basic with raw JS, and even more so with JQuery...
Here's a basic idea of what I'm saying (forgive me if the code is incorrect, I haven't used JQuery let alone frontend JS in some time now.
function displayConfirm() {
// Let's pretend the confirm "modal" has two buttons, one with id "okButton" and the other with "cancelButton". We shall use this later.
}
function updatePage(cancelled) {
// Here is where we would update the page depending on whether or not the confirm was cancelled.
}
$('#okButton').click(function() { // We don't use e, so we're just gonna ignore it... I think you can anyways, if JQuery throws a fit, use _ instead of e for the variable name as it just tells JS "hey, this variable, we don't use it."
updatePage(false);
}); // Consistently use semicolons, look into ESLint if you're forgetful like me lol
$('#cancelButton').click(function() {
updatePage(true);
});
It's as simple as that. Since JS doesn't allow you to just pause execution like that (well you can, but it just freezes everything else, such as when you don't ever break from an infinite loop, or recurse with no exit condition (unless JS does a Python and has a recursion limit)), we use just a callback for when that event is received. So unfortnately afaik you can't really wrap this into a function... Aside of maybe using promises? I don't think you can but it may be worth some research if you really, for whatever reason insist on using a function to wrap it all.
I have a couple of user interfaces where different asynchronous processes can be running simultaneously. When some of them finish, they need to do things like refresh some or all of the UI. To avoid the need to run the refresh multiple times, I use a setTimeout function to run the refresh so it runs only once even if 'triggered' from multiple simultaneous processes. e.g.:
var runCleanupTimeout;
function runCleanupOnce() {
if (runCleanupTimeout) clearTimeout(runCleanupTimeout);
runCleanupTimeout = setTimeout(function () {
refreshUI();
}, 250);
}
I know I can pass a callback into this also as well as pass the actual timeout as a variable to the function, but I'm starting to work with using Promises in functions that finish at some later time and I'm wondering how to implement such a thing as an abstract promise.
Currently I'm using a single timer (thus the static values and function calls - I seldom need more than one of these in a single UI, but when I do, I create a second variable and a second function with a fixed timeout)
I'd like to be able to write a generic utility-function as a promise so any time I want to do a run-only-once, I just call something like:
utilities.runOnce('someTimerId',250).then(
function() {
refreshUI();
}
);
I know I could instead use an array/associative array where I specify the id for the 'timer' and use a custom callback type structure. But I'm not entirely sure how this would work in a promise.then() structure. I saw one example using a .bind property but can't find a good reference on what bind() is doing in that case.
Any help to figure this out is appreciated.
Promises turned out to not be a good solution as a run-once type process only has one discreet resolve
This question already has answers here:
Stop page execution like the alert() function
(8 answers)
JavaScript: Overriding alert()
(12 answers)
Closed 4 years ago.
I'm looking at trying to recreate the behavior of a basic prompt box in JavaScript so that I can style it. Essentially, I want to be able to call a function (window.vars.prompt) and have it prompt the user, then return the value the user inputted. I want everything to happen synchronously, so that I can call it via a function and have it returned to the caller.
What I have so far freezes the program, then crashes it. I know why, but i have no Idea how to fix it. Anybody fix it?
Thanks!
(function () {
window.vars.userHasResponded = false
window.vars.userResponse = ""
window.vars.prompt = function(displayMsg) {
$(".input").html(`<div class='prompt'><h2>${displayMsg}</h2><div class="input"><input id="promptValue"/></div><div class="promptContros"><button>ok</button><button>cancel</button></div></div>`)
while (!window.vars.userHasResponded) {
if (window.vars.userResponse)
return window.vars.userResponse;
}
}
window.vars.confirmPrompt = function() {
$(".prompt").html("")
window.vars.userResponse = $("#promptValue").val()
window.vars.userHasResponded = window.vars.userResponse != "";
}
})()
The HTML for the box is stored in a div with a class of input
I'm looking at trying to recreate the behaviour of a basic prompt box in javascript...I want everything to happen synchronously, so that I can call it via a function and have it returned to the caller.
You cannot do so. prompt, alert, confirm, and beforeunload handlers are the only synchronous UI in the browser-based JavaScript world, and you cannot style them. It's impossible to replicate that behavior in your own UI widget.
Your own widget will have to be asynchronous.
In a comment on the question you've asked:
how come that while loop doesn't work?
Because the loop ties up the main UI thread by busy-waiting. User events in browser-based JavaScript queue up waiting for the thread to yield back to the browser (if the user even sees the updated DOM elements in the first place). Your busy-wait is keeping the current task active, meaning the events that follow it in the queue wait on your task to complete.
Instead, have your prompt and such return a Promise. Then, using it looks like this in a normal function:
prompt(/*...*/)
.then(result => {
// ...use the result
});
...or like this in an async function:
const result = await prompt(/*...*/);
(Error handling omitted for brevity.)
I want everything to happen synchronously
Unfortunately, this is impossible - script-writers can't write their own APIs that basically block until they're resolved without freezing the browser completely, they can only invoke a few special built-in methods that have that peculiar property. As is, your while loop's thread will run forever, preventing confirmPrompt from ever running. The thread never ends and so never gives confirmPrompt a chance to run.
Try using Promises instead. await, while not synchronous, can look more synchronous than using .then.
For the past two days I have been working with chrome asynchronous storage. It works "fine" if you have a function. (Like Below):
chrome.storage.sync.get({"disableautoplay": true}, function(e){
console.log(e.disableautoplay);
});
My problem is that I can't use a function with what I'm doing. I want to just return it, like LocalStorage can. Something like:
var a = chrome.storage.sync.get({"disableautoplay": true});
or
var a = chrome.storage.sync.get({"disableautoplay": true}, function(e){
return e.disableautoplay;
});
I've tried a million combinations, even setting a public variable and setting that:
var a;
window.onload = function(){
chrome.storage.sync.get({"disableautoplay": true}, function(e){
a = e.disableautoplay;
});
}
Nothing works. It all returns undefined unless the code referencing it is inside the function of the get, and that's useless to me. I just want to be able to return a value as a variable.
Is this even possible?
EDIT: This question is not a duplicate, please allow me to explain why:
1: There are no other posts asking this specifically (I spent two days looking first, just in case).
2: My question is still not answered. Yes, Chrome Storage is asynchronous, and yes, it does not return a value. That's the problem. I'll elaborate below...
I need to be able to get a stored value outside of the chrome.storage.sync.get function. I -cannot- use localStorage, as it is url specific, and the same values cannot be accessed from both the browser_action page of the chrome extension, and the background.js. I cannot store a value with one script and access it with another. They're treated separately.
So my only solution is to use Chrome Storage. There must be some way to get the value of a stored item and reference it outside the get function. I need to check it in an if statement.
Just like how localStorage can do
if(localStorage.getItem("disableautoplay") == true);
There has to be some way to do something along the lines of
if(chrome.storage.sync.get("disableautoplay") == true);
I realize it's not going to be THAT simple, but that's the best way I can explain it.
Every post I see says to do it this way:
chrome.storage.sync.get({"disableautoplay": true, function(i){
console.log(i.disableautoplay);
//But the info is worthless to me inside this function.
});
//I need it outside this function.
Here's a tailored answer to your question. It will still be 90% long explanation why you can't get around async, but bear with me — it will help you in general. I promise there is something pertinent to chrome.storage in the end.
Before we even begin, I will reiterate canonical links for this:
After calling chrome.tabs.query, the results are not available
(Chrome specific, excellent answer by RobW, probably easiest to understand)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference (General canonical reference on what you're asking for)
How do I return the response from an asynchronous call?
(an older but no less respected canonical question on asynchronous JS)
You Don't Know JS: Async & Performance (ebook on JS asynchronicity)
So, let's discuss JS asynchonicity.
Section 1: What is it?
First concept to cover is runtime environment. JavaScript is, in a way, embedded in another program that controls its execution flow - in this case, Chrome. All events that happen (timers, clicks, etc.) come from the runtime environment. JavaScript code registers handlers for events, which are remembered by the runtime and are called as appropriate.
Second, it's important to understand that JavaScript is single-threaded. There is a single event loop maintained by the runtime environment; if there is some other code executing when an event happens, that event is put into a queue to be processed when the current code terminates.
Take a look at this code:
var clicks = 0;
someCode();
element.addEventListener("click", function(e) {
console.log("Oh hey, I'm clicked!");
clicks += 1;
});
someMoreCode();
So, what is happening here? As this code executes, when the execution reaches .addEventListener, the following happens: the runtime environment is notified that when the event happens (element is clicked), it should call the handler function.
It's important to understand (though in this particular case it's fairly obvious) that the function is not run at this point. It will only run later, when that event happens. The execution continues as soon as the runtime acknowledges 'I will run (or "call back", hence the name "callback") this when that happens.' If someMoreCode() tries to access clicks, it will be 0, not 1.
This is what called asynchronicity, as this is something that will happen outside the current execution flow.
Section 2: Why is it needed, or why synchronous APIs are dying out?
Now, an important consideration. Suppose that someMoreCode() is actually a very long-running piece of code. What will happen if a click event happened while it's still running?
JavaScript has no concept of interrupts. Runtime will see that there is code executing, and will put the event handler call into the queue. The handler will not execute before someMoreCode() finishes completely.
While a click event handler is extreme in the sense that the click is not guaranteed to occur, this explains why you cannot wait for the result of an asynchronous operation. Here's an example that won't work:
element.addEventListener("click", function(e) {
console.log("Oh hey, I'm clicked!");
clicks += 1;
});
while(1) {
if(clicks > 0) {
console.log("Oh, hey, we clicked indeed!");
break;
}
}
You can click to your heart's content, but the code that would increment clicks is patiently waiting for the (non-terminating) loop to terminate. Oops.
Note that this piece of code doesn't only freeze this piece of code: every single event is no longer handled while we wait, because there is only one event queue / thread. There is only one way in JavaScript to let other handlers do their job: terminate current code, and let the runtime know what to call when something we want occurs.
This is why asynchronous treatment is applied to another class of calls that:
require the runtime, and not JS, to do something (disk/network access for example)
are guaranteed to terminate (whether in success or failure)
Let's go with a classic example: AJAX calls. Suppose we want to load a file from a URL.
Let's say that on our current connection, the runtime can request, download, and process the file in the form that can be used in JS in 100ms.
On another connection, that's kinda worse, it would take 500ms.
And sometimes the connection is really bad, so runtime will wait for 1000ms and give up with a timeout.
If we were to wait until this completes, we would have a variable, unpredictable, and relatively long delay. Because of how JS waiting works, all other handlers (e.g. UI) would not do their job for this delay, leading to a frozen page.
Sounds familiar? Yes, that's exactly how synchronous XMLHttpRequest works. Instead of a while(1) loop in JS code, it essentially happens in the runtime code - since JavaScript cannot let other code execute while it's waiting.
Yes, this allows for a familiar form of code:
var file = get("http://example.com/cat_video.mp4");
But at a terrible, terrible cost of everything freezing. A cost so terrible that, in fact, the modern browsers consider this deprecated. Here's a discussion on the topic on MDN.
Now let's look at localStorage. It matches the description of "terminating call to the runtime", and yet it is synchronous. Why?
To put it simply: historical reasons (it's a very old specification).
While it's certainly more predictable than a network request, localStorage still needs the following chain:
JS code <-> Runtime <-> Storage DB <-> Cache <-> File storage on disk
It's a complex chain of events, and the whole JS engine needs to be paused for it. This leads to what is considered unacceptable performance.
Now, Chrome APIs are, from ground up, designed for performance. You can still see some synchronous calls in older APIs like chrome.extension, and there are calls that are handled in JS (and therefore make sense as synchronous) but chrome.storage is (relatively) new.
As such, it embraces the paradigm "I acknowledge your call and will be back with results, now do something useful meanwhile" if there's a delay involved with doing something with runtime. There are no synchronous versions of those calls, unlike XMLHttpRequest.
Quoting the docs:
It's [chrome.storage] asynchronous with bulk read and write operations, and therefore faster than the blocking and serial localStorage API.
Section 3: How to embrace asynchronicity?
The classic way to deal with asynchronicity are callback chains.
Suppose you have the following synchronous code:
var result = doSomething();
doSomethingElse(result);
Suppose that, now, doSomething is asynchronous. Then this becomes:
doSomething(function(result) {
doSomethingElse(result);
});
But what if it's even more complex? Say it was:
function doABunchOfThings() {
var intermediate = doSomething();
return doSomethingElse(intermediate);
}
if (doABunchOfThings() == 42) {
andNowForSomethingCompletelyDifferent()
}
Well.. In this case you need to move all this in the callback. return must become a call instead.
function doABunchOfThings(callback) {
doSomething(function(intermediate) {
callback(doSomethingElse(intermediate));
});
}
doABunchOfThings(function(result) {
if (result == 42) {
andNowForSomethingCompletelyDifferent();
}
});
Here you have a chain of callbacks: doABunchOfThings calls doSomething immediately, which terminates, but sometime later calls doSomethingElse, the result of which is fed to if through another callback.
Obviously, the layering of this can get messy. Well, nobody said that JavaScript is a good language.. Welcome to Callback Hell.
There are tools to make it more manageable, for example Promises and async/await. I will not discuss them here (running out of space), but they do not change the fundamental "this code will only run later" part.
Section TL;DR: I absolutely must have the storage synchronous, halp!
Sometimes there are legitimate reasons to have a synchronous storage. For instance, webRequest API blocking calls can't wait. Or Callback Hell is going to cost you dearly.
What you can do is have a synchronous cache of the asynchronous chrome.storage. It comes with some costs, but it's not impossible.
Consider:
var storageCache = {};
chrome.storage.sync.get(null, function(data) {
storageCache = data;
// Now you have a synchronous snapshot!
});
// Not HERE, though, not until "inner" code runs
If you can put ALL your initialization code in one function init(), then you have this:
var storageCache = {};
chrome.storage.sync.get(null, function(data) {
storageCache = data;
init(); // All your code is contained here, or executes later that this
});
By the time code in init() executes, and afterwards when any event that was assigned handlers in init() happens, storageCache will be populated. You have reduced the asynchronicity to ONE callback.
Of course, this is only a snapshot of what storage looks at the time of executing get(). If you want to maintain coherency with storage, you need to set up updates to storageCache via chrome.storage.onChanged events. Because of the single-event-loop nature of JS, this means the cache will only be updated while your code doesn't run, but in many cases that's acceptable.
Similarly, if you want to propagate changes to storageCache to the real storage, just setting storageCache['key'] is not enough. You would need to write a set(key, value) shim that BOTH writes to storageCache and schedules an (asynchronous) chrome.storage.sync.set.
Implementing those is left as an exercise.
Make the main function "async" and make a "Promise" in it :)
async function mainFuction() {
var p = new Promise(function(resolve, reject){
chrome.storage.sync.get({"disableautoplay": true}, function(options){
resolve(options.disableautoplay);
})
});
const configOut = await p;
console.log(configOut);
}
Yes, you can achieve that using promise:
let getFromStorage = keys => new Promise((resolve, reject) =>
chrome.storage.sync.get(...keys, result => resolve(result)));
chrome.storage.sync.get has no returned values, which explains why you would get undefined when calling something like
var a = chrome.storage.sync.get({"disableautoplay": true});
chrome.storage.sync.get is also an asynchronous method, which explains why in the following code a would be undefined unless you access it inside the callback function.
var a;
window.onload = function(){
chrome.storage.sync.get({"disableautoplay": true}, function(e){
// #2
a = e.disableautoplay; // true or false
});
// #1
a; // undefined
}
If you could manage to work this out you will have made a source of strange bugs. Messages are executed asynchronously which means that when you send a message the rest of your code can execute before the asychronous function returns. There is not guarantee for that since chrome is multi-threaded and the get function may delay, i.e. hdd is busy.
Using your code as an example:
var a;
window.onload = function(){
chrome.storage.sync.get({"disableautoplay": true}, function(e){
a = e.disableautoplay;
});
}
if(a)
console.log("true!");
else
console.log("false! Maybe undefined as well. Strange if you know that a is true, right?");
So it will be better if you use something like this:
chrome.storage.sync.get({"disableautoplay": true}, function(e){
a = e.disableautoplay;
if(a)
console.log("true!");
else
console.log("false! But maybe undefined as well");
});
If you really want to return this value then use the javascript storage API. This stores only string values so you have to cast the value before storing and after getting it.
//Setting the value
localStorage.setItem('disableautoplay', JSON.stringify(true));
//Getting the value
var a = JSON.stringify(localStorage.getItem('disableautoplay'));
var a = await chrome.storage.sync.get({"disableautoplay": true});
This should be in an async function. e.g. if you need to run it at top level, wrap it:
(async () => {
var a = await chrome.storage.sync.get({"disableautoplay": true});
})();
I am using some API functionality with AddThis. I found an API example that will create an alert box when AddThis fully loads on the page. Is there another event listener that I can use to create a popup box after a person closes one of the sharing popup windows? Basically I want to check and see if the AddThis popup window is closed, then trigger another alert box after that. I will post the example and the link to the reference for the API. I do not understand javascript event listeners very well so I apologize for any ignorance in advance.
link to API documentation for AddThis: http://support.addthis.com/customer/portal/articles/381263-addthis-client-api#events-types
the example used:
function addthisReady(evt) {
alert('AddThis API is fully loaded.');
}
addthis.addEventListener('addthis.ready', addthisReady);
I found it a little difficult to understand your question and If I am not wrong,you want to execute a function after completion of some other function.In this context,I guess you can understand the basic principal and apply it and solve your prolem yourself.
Here is my answer:
"Javascript is single threaded".
So,what does this means:
Javascript runs code sequentially.It is not possible to run two
different pieces of Javascript code at the same time because it does
not support multithreading.
A simple solution:
execute_me_first() ;
execute_me_on_completion();
Another solution:
Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.
function doSomething(callback) {
execute_me_first() or some code;//This will execute first
callback('param1','param2');// Call the callback
}
function execute_me_on_completion(param1,param2) {
// I'm the callback
alert("hi ,I am executed right after completion of execute_me_first() function");
}
doSomething(execute_me_on_completion);
I think you're looking for the addthis.menu.close event, which can be found in our documentation here: http://support.addthis.com/customer/portal/articles/381263-addthis-client-api#events
The code will look something like this:
function addthisClose(evt) {
alert('AddThis menu has closed.');
}
addthis.addEventListener('addthis.menu.close', addthisClose);
Thanks for using AddThis!