This question already has answers here:
Where do the parameters in a javascript callback function come from?
(3 answers)
Closed 4 years ago.
As seen here from Twilio's documentation, how does the following code work? We have a connection class and an on method. If I haven't previously defined what hasEarlyMedia, showRingingIndicator, or playOutgoingRinging mean, then how does the on method know what they mean and what to do with them? Thanks.
connection.on('ringing', function(hasEarlyMedia) {
showRingingIndicator();
if (hasEarlyMedia) { playOutgoingRinging(); }
});
Maybe is easier to understand if we rewrite the code like this:
// when the Connection has entered the ringing state,
// call handleRingingEvent (callback function) and pass an argument,
// a boolean denoting whether there is early media available from the callee
connection.on('ringing', handleRingingEvent);
function handleRingingEvent(hasEarlyMedia) {
showRingingIndicator();
if (hasEarlyMedia) {
playOutgoingRinging();
}
}
// if not defined somewhere else
function showRingingIndicator() {
// do something
}
// if not defined somewhere else
function playOutgoingRinging() {
// do something
}
I hope this helps.
hasEarlyMedia is an argument. Please check
showRingingIndicator(); and playOutgoingRinging(); method must be defined somewhere. Must be function declared in your one of the library which you have included in your file.
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
Recently, I've come across this problem where I had two methods in a class. One was referring to another but the other wasn't being recognized even though I could execute them individually.
class ButtonProcessor {
buttonClick() {
this.otherMethod();
}
otherMethod() {
console.log("This does not work!");
}
}
var buttonProcessor = ButtonProcessor;
document.getElementById("button").onclick = buttonProcessor.buttonClick;
The first method was called from a button click which was associated with a callback to that method.
One solution I found for this is to make the method that is called by the button a seperate function from the class and make it reference a class object that was already being used else-where. This is because apparently, when a method is referenced in a callback, using this to refer to another method doesn't work, because the callback only considers that one method.
class ButtonProcessor {
otherMethod() {
console.log("This does work!");
}
}
var buttonProcessor = ButtonProcessor;
function buttonClick() {
buttonProcessor.otherMethod();
}
document.getElementById("button").onclick = buttonProcessor.buttonClick;
Could there be another way to fix this?
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I save information locally in my chrome extension?
(2 answers)
Closed 5 years ago.
I have a string which I need in multiple functions. Therefore I want to save it in a variable. But when I try to assign it inside a function it doesn't update the variable.
var auth_code = "na";
function safeAuthCode(authcode){
auth_code = authcode;
console.log(auth_code);
}
"auth_code" prints just fine in the console at that point, but when I try to use it later it just contains "na". Not sure what I'm doing wrong tbh :/
Edit:
This is the function in which safeAuthCode is called:
function auth(){
chrome.identity.launchWebAuthFlow({
"url": "https://accounts.spotify.com/authorize?client_id="+client_id+
"&redirect_uri="+ encodeURIComponent(redirectUri) +
"&response_type=code"+
"&scope=" + encodeURIComponent(scopes),
"interactive": true
},
function(redirect_url) {
var url = new URL(redirect_url);
var code = url.searchParams.get("code");
safeAuthCode(code);
});
}
I am assuming that the problem you are having is because of the global variable that either gets overwritten in a different part of the code, or because your code at a certain point in time reloads, and the initial value gets reset.
To save such authentication code, you could make use of the sessionStorage object of your browser.
To make sure you only have 1 such object, you could use the const keyword to define your variables (in case another definition of that variable would come at a later time, you should get an error thrown)
const authorisationSettings = {
get code() {
return sessionStorage.getItem('authorisationCode') || 'na';
},
set code(value) {
return sessionStorage.setItem('authorisationCode');
}
};
function saveAuthorisationCode( code ) {
authorisationSettings.code = code;
}
saveAuthorisationCode( 'test' );
console.log( authorisationSettings.code );
This snippet doesn't work on stackoverflow, so you can find the jsfiddle here
It happens because of when your function is executed, in lexical environment of that function is already exist authcode variable and you are trying to set this one instead of global authcode
You need to change name of global variable or param of the fuction...
This question already has an answer here:
Cannot pass module functions to Page
(1 answer)
Closed 6 years ago.
i'm getting a ReferenceError when i call a function i defined myself inside the page.evaluate() of Phantom; what is the proper way to do that ?
for example:
function mySweetFunction(item) {
// process item....
}
page.evaluate(function(){
var item= document.getElementsById('item');
mySweetFunction(item);
});
then i'll get the error:
ReferenceError: Can't find variable: mySweetFunction
What is the proper way to do this ?
mySweetFunction is quite big, and i would prefer to keep it out of page.evaluate(...) if possible.
If you want to use a function inside page.evaluate() you have to put it there first:
page.evaluate(function(){
function mySweetFunction(item) {
// process item....
}
var item = document.getElementsById('item');
mySweetFunction(item);
});
This question already has answers here:
How can we know if a function is called from console or from source code
(3 answers)
Closed 7 years ago.
I want a particular JavaScript function to behave differently depending on if it's called within JavaScript code referenced from an HTML page or called from within a console. Is this possible? Something like the following:
function mySpecialFunc() {
if (inConsole())
console.log("You called me from the console!");
else
console.log("You called me from an HTML page or a JavaScript file linked from an HTML page, I think.");
}
Does something equivalent to the inConsole() function above exist?
Does this exist for at least just Chrome specifically, or Firefox specifically?
One way is to throw an error and check the stack trace for a string that is unique to the console's injection. Something like "InjectedScript"
Here is an example that works.
var f = function(){
var injected;
try {
throw new Error();
} catch (e) {
injected = e.stack.match('InjectedScript');
}
if (injected) {
console.log("Called from console");
} else {
console.log("Called from code");
}
}
// Add it to window so we can call it from the console.
window.f = f;
f();
Unfortunately there is no way to tell via system input, but you can do it "Manually" in a sense using overflow/overload functions. See here for a excellent tutorial on how to use overflow/overload in js.
So in your code that calls the function in javascript add an additional argument to the call that will tell the function it is not called from the console.
mySpecialFunc() <---- From console
mySpecialFunc(value) <---- From code
This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 6 years ago.
I've been trying to work out how to pass additional parameters to a javascript callback function.
In similar posts users have succeeded using anonymous function (these are new to me so I may have been doing them wrong) but I just can't get them to fire.
The below is what I have now, I need to be able to pass the itemId to the function "ajaxCheck_Callback" as well as the response.
Hope this makes sense.
Thanks for the help.
function delete(itemId)
{
selectpage.ajaxCheck(itemId, ajaxCheck_Callback);
}
Function ajaxCheck_Callback(response)
{
alert(response);
alert(itemId);
}
Thanks for the help guys. I now get undefined on my alert whereas previously this was alerting correctly.
function delete(itemId)
{
selectpage.ajaxCheck(itemid, function () {ajaxCheck_Callback(itemid); });
}
function ajaxCheck_Callback(response)
{
alert(response);
alert(itemId);
}
The way is usually done is to use an anonymous function.
function deleteItem(itemId) {
selectpage.ajaxCheck(itemId, function() { ajaxcheck_Callback(itemId); });
}
function ajaxCheck_Callback(response)
{
alert(response);
}
Careful with your syntax, there are some errors in there. The function keyword has a lower-case f and you can't have a function named delete, that's a reserved keyword.
As your question mentions, you can do it using an anonymous function:
function deleteItem(itemId)
{
selectpage.ajaxCheck(itemId, function ()
{
ajaxCheck_Callback(itemId);
});
}
// Note, lowercase 'f' in 'function'
function ajaxCheck_Callback(response)
{
alert(response);
}
It can also be done using a named function, which you might find more readable:
function deleteItem(itemId)
{
function onAjaxCheck()
{
ajaxCheck_Callback(itemId);
}
selectpage.ajaxCheck(itemId, onAjaxCheck);
}
N.B. as #Xeon06 points out, delete is a reserved word, so that is not a valid function name.
Create an anonymous function, which calls your callback, and supplies the needed parameter.
function deleteItemById(itemId)
{
selectpage.ajaxCheck(itemId, function() { ajaxCheck_Callback(itemId); });
}
The anonymous function will create a closure over itemId, and therefore will still have access to this value even after the original call to delete has long since ended.
For completeness, also note that delete is a reserved word in JavaScript; you need to name this function something else.