PhantomJS: call a user defined/custom function within phantomjs [duplicate] - javascript

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);
});

Related

Why is a javascript function unaccessible from another script file? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I have a problem I've been searching SO for answers to, but nothing seem to do it for me. I've referenced a question that mimics my problem but the solution still don't solve my problem.
Accessing function in another .js file with $.getScript
My problem is as I've mentioned similar. I can't access a method inside a script file from another script file. These are my codes:
page.js
$(document).ready(function () {
$.getScript('script.js').done(function () {
$('#build').append(literals.test()); // $('#build') is a span tag in the HTML-file.
}).fail(function () {
console.warn('Unable to load script file.');
});
});
script.js
(function ($) {
var literals = {
test: function () {
return 'Hello world!';
}
};
})(jQuery);
This still returns the following error even though I've built it almost exactly the same way as in the answer of the referenced question.
Uncaught ReferenceError: literals is not defined at Object.<anonymous>
What am I doing wrong here?
Because when you create a closure, anything inside of it is only visible to other things in that scope.
In JS, all functions are closures.
(function(){
// this is a closure
})()
If you want to be able to get the literals functions from outside of the closure, one option is to return it from the function...
const literals = (function($){
return {
test: function () {
return 'Hello world!';
}
};
})(jQuery);
console.log(literals.test());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript Variable not updating/saving [duplicate]

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...

exctracting a variable from a jquery method [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I want to extract the variable response from the mentionsInput() method and using it outside this method, but when I try an alert() on this variable it's empty.
jQuery(document).ready(function() {
var choix = $('#choixaide').val();
var choix_sous_theme1 = $('#choix_sous_theme1aide').val();
$('textarea.mention1').mentionsInput('val', function(text) {
var response = text;
});
alert(response);
});
Thanks for your help.
As you have it now, response is only available within the scope of your mentionsInput method, but not outside of it.
Additionally, when running your code, I see the following error:
Uncaught TypeError: $(...).mentionsInput is not a function"...
Are you sure you've properly loaded the jquery.mentionsInput UI component? You'll need to solve for this error first, if you are also encountering this.
Then, you'll need to declare the variable response prior to and outside of your mentionsInput method, and then set it within mentionsInput. The value set for response should then be available in the same scope as your alert call.
I think this should do the trick:
jQuery(document).ready(function() {
var choix = $('#choixaide').val();
var choix_sous_theme1 = $('#choix_sous_theme1aide').val();
var response = $('textarea.mention1').val();
alert(response);
});

How to know when a JavaScript function is called from a console? [duplicate]

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

Javascript: Function overwrite with passing arguments [duplicate]

This question already has answers here:
Passing arguments forward to another javascript function
(5 answers)
Closed 8 years ago.
I am using Winston (Logger for nodejs).
In my script i call:
log.error("my error", {input: [1,2]});
console show me:
error: my error input=[1, 2]
What i want to do: don' call at log.error(null)
In some functions i dynamically call the log.error with a variable and dont know if the variable are NULL or have a value. If i call log.error(null) he write "error:" to the console.
I tried with this:
log.error = (function () {
var old = log.error;
return function newerror() {
if (arguments.length !== 0) {
old(arguments);
}
};
})();
But now i got:
error: 0=my error, input=[1, 2]
as output.
My Question
how i can call the log.error() function with die arguments given (arguments-var in javascript is a object).
Function style:
function foo(arg1,arg2,...)
I want something like:
foo.call(myargumentsobj);
oh i got it:
old.apply(this, arguments);

Categories

Resources