How do I make custom JavaScript console commands? - javascript

I've been trying to make custom console commands with JavaScript with no success. There seem to be no sources about my question.
When I say "JavaScript Console Commands" I mean I'd like to make my own commands from the console. For example, if the visitor types "custom.command()" in my website's console area, I want the output to be: console.log("This is my custom command");.

You don't have to do anything special; just create an object at global scope with functions on it, and the user will be able to use it from the devtools console.
For instance (in a script, not a module):
const custom = {
command() {
console.log("This is my custom command.");
},
};
Because that's at global scope, it creates a global, and so it is accessible in the console when your page is open.
(It doesn't have to be an object; you could just create a function at global scope, but your example usage was using an object.)
If you wanted to do this from a module, since the top level of a module isn't global scope, you'd have to do the same kind of thing you have to do to create a global in a function, which is covered by the answers to this question (in your case, it' basically assign to a property on window: window.custom = { /*...*/ };).

Related

Set function default this value

Background:
I am running a sandboxed iframe which only has the permission "allow-scripts". In the sandbox a script is loaded with custom js provided by the user. Now i want to manage access to global functions/objects like XMLHttpRequest. Currently i achieve that with the following code:
const CLEARED_WINDOW_SCOPE= {};
const scope = { /* Here goes the globals the script should have access too */};
const propertyNames = Object.getOwnPropertyNames(window);
for(let property of propertyNames){
CLEARED_WINDOW_SCOPE[property] = undefined;
}
with(CLEARED_WINDOW_SCOPE){
with(scope){
(function (window, self, frames, globalThis){
${scriptContent}
}).call(scope, scope, scope, scope, scope);
}
}
The script does the following:
Create object with all window property names set to undefined
Create object with all properties the user should have access too
Wrap the user code with two with statements the first clears all globals the second grands access to the defined ones
Wrap the user code with a function that is called with the scope as this value
So far everything works perfectly as excepted.
Problem:
The main problem that i have right now is that when a user defines a function like that:
function aFunction(){
console.log(this);
}
He gains access to the normal window object because the default this value within a function is the window.
Question:
Is it somehow possible to change the default this value of a function to the this value of the surrounding scope. Since the user creates the script i can't wrap all function calls with aFunction.bind(scope). Or is there any other value to prevent the access to the global window object?
Is it somehow possible to change the default this value of a function to the this value of the surrounding scope.
No, but you can do the next best(?) thing: setting it to undefined. Just force strict mode:
"use strict";
// User's code
(function (){
console.log(this)
})();
Also, I'm not a JavaScript security expert, but JS sandboxing is a really complex topic because of things like prototype pollution.
Edit: As CherryDT noted in the comments, this method is not completely secure. Users can still access the <iframe> window by creating a function with the Function constructor, for example. Also, a reference to the main window can be obtained through the <iframe> window (window.parent).
It's maybe OK to use this solution for user-supplied code (since users can just open the DevTools console and start typing), but make sure the code comes from the user and never from a URL search parameter, for example. If the code is completely distrusted, I would recommend to use a well-known library like Google Caja.

Overriding jQuery function loses 'this' scope

I am trying to implement the following answer from another question:
https://stackoverflow.com/a/26469105/2402594
Basically I need to add an extra check to a jQuery function. The following code is in jQuery library:
But I can't modify the original jQuery, so I am creating a patch in a separate file. What I am doing is overriding the find function and add functionality as follows:
(function() {
var originalFind = jQuery.fn.find;
jQuery.fn.find = function () {
try {
document === document;
}
catch (err) {
document = window.document;
}
return originalFind.apply(this, arguments);
};
})();
The function is overridden correctly, however, when the code calls 'find', my 'try' doesn't throw any exception when it should because the scope is different than the one inside the Sizzle function, so the original issue is still there.
I have also tried duplicating all of the Sizzle code, adding my modification and assigning it to jQuery.fn.find as done above, however the scope issue is still there and some crashes happen.
I need 'document' to be set before it reaches the following check or it crashes due to permission denied:
How could I share the scope so that the try/catch can be done correctly? Is it even possible? Any other ideas?
Thank you
As we all known, JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.
So, if the document is defined in the JQuery library function, I think you can't access it. You could try to define a global variable to store the document, then, you can access it in the JQuery library function and the override function.
More details about Javascript Scope, check these links: link1 and link2

Make variable accessible like window

Lets say I have one variable var car = 'VW' in index.html
index.html is the binding of my application, from there I access several modules:
<script>
var car = 'VW';
var Initializer = require('./js/initializer');
Initializer.check_requirements();
</script>
Now in initializer I try to access this variable what does not work.
var Initializer = {
check_requirements: function(){console.log(car)};
};
module.exports = Initializer;
However when I attach the variable car to window:
window.car = 'VW';
Then Im able to access it in my module over window.car;
How do I create an global variable car that I can also access in my modules, so that I do not have to attach to window?
Thanks
In a browser context, a "global" variable is in fact a property of the window object, which acts as the global context. The syntax you have in your question, a bare var statement in a script tag in an HTML page, will in fact add that var name as a property to the window. However, since you're using what looks like a CommonJS require statement here, which is not natively supported in most browsers, there's probably a compile step you're not including in your question that's preventing this from working the way you expect.
However, the short answer is, don't do this if you can avoid it. Most applications of global variables are better accomplished with parameters, e.g. Initializer.check_requirements(car);, or in a separate module storing configuration settings, or other approaches.

After modifying attributes on a node.js vm context (sandbox), the modifications aren't seen by code in the context

Background
I'm working on tests for the Backbone.dualStorage plugin for Backbone.js that replaces Backbone.sync.
This is a browser plugin, but I'm using jasmine-node to test it. I load the coffeescript source into the node environment to simulate the browser window using vm.createContext:
vm = require 'vm'
fs = require 'fs'
coffee = require 'coffee-script'
backboneDualstoragePath = './backbone.dualstorage.coffee'
source = fs.readFileSync(backboneDualstoragePath, 'utf8')
window = require('./global_test_context.coffee').window
context = vm.createContext window
coffee.eval source, sandbox: context, filename: backboneDualstoragePath
exports.window = context
This works great - in my tests, I can access window.foo, where foo is an attribute exported on the window object in global_test_context.coffee.
I can use Jasmine spies on and redefine methods on any object nested under the window sandbox. Eg:
spyOn(window.Store.prototype, 'create').andReturn(true)
window.Store.create() # The spy is called
window.localsync.create() # This function instantiates a Store object and calls create on it
# The spy is called
However if I try to spy on or otherwise modify the context's direct attributes, the change is not seen inside the sandbox context:
spyOn(window, 'localsync').andReturn(true)
window.localsync() # The spy is called
window.dualsync() # This function references the global localsync
# The original localsync is called
The vm.createContext documentation says:
A (V8) context comprises a global object together with a set of
build-in objects and functions. The optional argument initSandbox
will be shallow-copied to seed the initial contents of the global object used by the context.
So it sounds like it copies the attributes from my window variable into the vm context. When I spy on or otherwise modify window after this point, I am working with the vm context, which I export as an attribute named window. Therefore I think that the paragraph above is irrelevant, but I wanted to include it in case I'm wrong.
The Question
The flow of events boils down to this:
window = vm.createContext({globalVariables: forTesting...})
# similiar to vm.runInContext(backboneDualstorageSource, window)
coffee.eval(backboneDualstorageSource, sandbox: window)
# localsync and dualsync are both defined in the backboneDualstorageSource
spyOn(window, 'localsync')
window.dualsync() # calls the original localsync instead of the spy
Why is it that after modifying attributes on the vm context, references to those "global" attributes/functions inside the vm don't change? I want to understand this.
How can I work around this so that I can modify/spyOn globals in the browser script I'm testing?
Feel free to look at the source to get a better idea of how things are actually written compared to the snippets in this question.
Edit
I was able to work around this issue by creating the spy inside an eval that runs in the context, like the rest of the tested code. See https://github.com/nilbus/Backbone.dualStorage/commit/eb6c2b21
Could someone explain why I'm able to modify global variables within the context but not outside the context, even though I have access to them?
Modifying context after eval is not affecting already evaluated scripts, if I understand your issue correctly. If you don't need to add new members to context, and just need to modify existing ones, use getters, which is working fine in latest node (0.8.x for now).
don't go down one level with the global key, try this:
window = vm.createContext({variablesForTesting.. })

Sandboxing javascript module

Is it possible to sandbox javascript module from DOM manipulation? Fo example
var Core = {
register: function(config){config.init()},
publicApi: {
msgbox: function(msg){alert(msg)}
}
}
Core.register({
name: 'testmodule',
init: function(){
/* from there i want to see only function defined in Core.publicApi, no jQuery direct access, no DOM */
}
});
Well, somewhat: you can sandbox the function, but its callees will also be sandboxed. That means even stuff in Core.publicApi won't be able to access document and the like. Or, at least, there's no bulletproof sandboxing in Javascript that will allow that bridging.
You can cripple what's available by temporarily overwriting the window variable:
var window = {"Core": Core};
But then no global variable (even such as alert) will exist for the callees. This will most likely break your API.
You can add another member (like _unsandboxed or whatever) into the new window variable to allow your API to access the members. But, as I said, it's not bulletproof since sandboxed functions can still access _unsandboxed.

Categories