getting sessionid with javascript - javascript

Under the headline:
Finding the session id with javascript in the browser
from this link:
Link to Autopilot
it says that I with the line of code can capture the Autopilot session id.
var sessionId = AutopilotAnywhere.sessionId;
I tried to set the line of code in the console, but I get undefined:
I am not quite sure how to use this line of code. Can anybody see how I use the line of code?

Try it:
function getJSessionId(){
var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
if(jsId != null) {
if (jsId instanceof Array)
jsId = jsId[0].substring(11);
else
jsId = jsId.substring(11);
}
return jsId;
}

Related

Jquery The name '' is does not exists in the current context

Although there are several same questions, I'm very curious regarding this specific case.
jQuery(document).ready(function () {
if ($('#msg').val() != '' && $('#msgSuccess').val() == 'true') {
var msg = $('#msg').val();
var t = $('#msg').val().toString();
toastr.success("#_localizer[t]");
}
});
variable t has some message which represents the key for my localization file.
I have issue to pass that variable (string) to my mvc _localizer.
Where I go wrong with this?
If I add simple console.log(t) it works. So Im guessing that is the localizer is a problem.
I'm using #inject IViewLocalizer _localizer from AspNetCore.Mvc.Localization

assigning variables only if undefined in javascript

I'm trying to extract two keywords from a url in this format
localhost:3000/"charactername"/"realmname"
where I want to exctract "charactername" and "realmname" and assign them to variables.
I use:
var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname = req.url.split("/")[2];
console.log(realmname);
Everything works fine and dandy at first, but then it seems a request is made for a "favicon.ico", and my variables become undefined since there is a new request url. I tried solving this by encapsulating the code snippet in an if statement like this:
if(req.url !== '/favicon.ico'){
var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname = req.url.split("/")[2];
console.log(realmname);
}
The console.log outputs tells me the variables are set to their correct values, it never says it is undefined so it seems to work.. However, when the next part of the code is executed:
if(charactername.length > 0){
res.writeHead(200, {'Content-Type': 'text/html'});
renderer.view("header", {}, res);
//get json from battle.net
var characterProfile = new Profile(charactername, realmname);
//on "end"
characterProfile.on("end", function(profileJSON){
//Show profile
//Store values we need
var values = {
avatarURL: profileJSON.thumbnail,
charactername: profileJSON.name,
realmname: profileJSON.realm,
level: profileJSON.level
}
//Simple response
renderer.view("profile", values, res);
renderer.view("footer", {}, res);
res.end();
});
I get an error saying cannot read property length of undefined. So it seems the variables become undefined somehow anyway. Anyone got a clue on how to solve this?
if(x === undefined){
//do something
}
This checks if the variable is undefined, however I suggest you check what is causing the error in the first place.
if(charactername && charactername.length > 0){
...

PhantomJS - Trying to find out if an element is empty or not

I'm trying to write a simple PhantomJS script where I find an element by ID and determine if it is empty of not. I've tried a few suggested things such as .childNodes.length, .textContent, etc.
These either result in a null error:
TypeError: null is not an object (evaluating 'document.getElementById('idname').childNodes')
Or phantom just crashes and refuses to check the links at all, usually this happens if I run my script twice in a row without much pause. And it will sometimes sit and do nothing.
I've written other scrapers that effectively used getElementById in this way, and they were successful, although there I was just checking if the element existed by checking if it was !== null. Checking manually, this element does exist in all the pages I'm checking, it's just that it sometimes has content and sometimes doesn't (it's a div). Anyway, here is my code:
var fs = require('fs')
var urls = fs.read('urls.txt').split('\n');
var page;
page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
function check_link(url){
page = require('webpage').create();
page.open(url, function(status){
if (status !== 'success') {
console.log('Unable to access network');
} else {
var error = page.evaluate(function() {
return document.getElementById('error-message');
});
console.log(error.childNodes.length);
fs.write('results.csv', error.childNodes.length + ', ' + url + '\n', 'a');
page.release();
setTimeout(next_link, 1000);
}
});
}
function next_link(){
var url = urls.shift();
console.log(url);
if(!urls){
phantom.exit(0);
} else{
check_link(url);
}
}
next_link();
PhantomJS provides access to the sandboxed page context (DOM context) through page.evaluate() with the following note:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
Closures, functions, DOM nodes, etc. will not work!
So you cannot pass the DOM node out of the page context, but you can do everything you want with it in the page context and then pass out the result.
var errors = page.evaluate(function() {
var e = document.getElementById('error-message');
return (e && e.childNodes) ? e.childNodes.length : -1
});
console.log(errors);

Error when decoding base64 with buffer. First argument needs to be a number

I am working on running different encoding statements based on the URL.
My code:
var parsedUrl = url.parse(req.url, true);
var queryAsObject = parsedUrl.query;
var myString = queryAsObject["string"];
var myFunction = queryAsObject["function"];
if (myFunction == "encodeb64") {
var bufEncode = new Buffer(JSON.stringify(myString));
var myEncode = bufEncode.toString('base64');
console.log(myEncode);
}
else {
console.log("Error1");
};
if (myFunction == "decodeb64") {
// var bufDecode = new Buffer(myEncode, 'base64');
// var myDecode = bufDecode.toString('utf8');
var myDecode = new Buffer(myEncode, 'base64').toString('utf8');
console.log(myDecode);
}
else {
console.log("Error2");
};
URL used: http://127.0.0.1:8020/?string=text&function=decodeb64
The issue is that I am having is with the last if statement. If its looking for decodeb64 and the first statement is looking for encodeb64 it crashes when function=decodeb64 is in the URL. If both if statements are looking for either encodeb64 or decodeb64, it runs perfectly. It also works if function=encodeb64 is in the URL.
The error message I get is:
buffer.js:188
throw new TypeError('First argument needs to be a number, ' +
^
It points to:
var myDecode = new Buffer(myEncode, 'base64').toString('utf8');
The given number on the error is pointed to the n in new.
I have located the problem to be inside the decode if statement by moving and reversing the order on the code.
As you can see in my code notes, I have tried two different methods of decoding with no success.
The reason that it crashes I believe is that when function=decode64, the variable myEncode is not declared and initialized, as the if(myFunction=="encode64") block is not run.
So when the code tried to new Buffer(myEncode...) it would fail as myEncode is undefined.
I think you meant to code :
var myDecode = new Buffer(myString, ...)
instead

How might I get the script filename from within that script?

I'm pretty sure the answer is no, but thought I'd ask anyway.
If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:
var scriptName = ???
if (typeof jQuery !== "function") {
throw new Error(
"jQuery's script needs to be loaded before " +
scriptName + ". Check the <script> tag order.");
}
Probably more trouble than it's worth for dependency checking, but what the hell.
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);
Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6
See also: How may I reference the script tag that loaded the currently-executing script?
I'm aware this is old but I have developed a better solution because all of the above didn't work for Async scripts. With some tweaking the following script can cover almost all use cases. Heres what worked for me:
function getScriptName() {
var error = new Error()
, source
, lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/)
, currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/);
if((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] != "")
return source[1];
else if((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1];
else if(error.fileName != undefined)
return error.fileName;
}
Not sure about support on Internet Explorer, but works fine in every other browser I tested on.
You can use...
var scripts = document.getElementsByTagName("script"),
currentScriptUrl = (document.currentScript || scripts[scripts.length - 1]).src;
currentScript() is supported by all browsers except IE.
Make sure it's ran as the file is parsed and executed, not on DOM ready or window load.
If it's an empty string, your script block has no or an empty src attribute.
In Node.js:
var abc = __filename.split(__dirname+"/").pop();
Shog9's suggestion more shorter:
alert("loading: " + document.scripts[document.scripts.length-1].src);
You can return a list of script elements in the page:
var scripts = document.getElementsByTagName("script");
And then evaluate each one and retrieve its location:
var location;
for(var i=0; i<scripts.length;++i) {
location = scripts[i].src;
//Do stuff with the script location here
}
As the "src" attribute holds the full path to the script file you can add a substring call to get the file name only.
var path = document.scripts[document.scripts.length-1].src;
var fileName = path.substring(path.lastIndexOf('/')+1);
I had issues with the above code while extracting the script name when the calling code is included inside a .html file.
Hence I developed this solution:
var scripts = document.getElementsByTagName( "script" ) ;
var currentScriptUrl = ( document.currentScript || scripts[scripts.length - 1] ).src ;
var scriptName = currentScriptUrl.length > 0 ? currentScriptUrl : scripts[scripts.length-1].baseURI.split( "/" ).pop() ;
You can try putting this at the top of your JavaScript file:
window.myJSFilename = "";
window.onerror = function(message, url, line) {
if (window.myJSFilename != "") return;
window.myJSFilename = url;
}
throw 1;
Make sure you have only functions below this. The myJSFilename variable will contain the full path of the JavaScript file, the filename can be parsed from that. Tested in IE11, but it should work elsewhere.
If you did't want use jQuery:
function getCurrentFile() {
var filename = document.location.href;
var tail = (filename.indexOf(".", (filename.indexOf(".org") + 1)) == -1) ? filename.length : filename.lastIndexOf(".");
return (filename.lastIndexOf("/") >= (filename.length - 1)) ? (filename.substring(filename.substring(0, filename.length - 2).lastIndexOf("/") + 1, filename.lastIndexOf("/"))).toLowerCase() : (filename.substring(filename.lastIndexOf("/") + 1, tail)).toLowerCase();
}
What will happen if the jQuery script isn't there? Are you just going to output a message? I guess it is slightly better for debugging if something goes wrong, but it's not very helpful for users.
I'd say just design your pages such that this occurrence will not happen, and in the rare event it does, just let the script fail.
The only way that is waterproof:
var code = this.__proto__.constructor.toString();
$("script").each(function (index, element) {
var src = $(element).attr("src");
if (src !== undefined) {
$.get(src, function (data) {
if (data.trim() === code) {
scriptdir = src.substring(0, src.lastIndexOf("/"));
}
});
}
});
"var code" can also be the function name, but with the prototype constructor you don't have to modify anything. This code compares its own content against all present scripts. No hard coded filenames needed anymore.
Korporal Nobbs was in the right direction, but not complete with the comparison.

Categories

Resources