user5672329
user5672329

Reputation:

Browserify private global variable

How can I create a private custom global variable with browserify?
For example, a variable wich is accessible from all the browserify files (require()) but not outside the browserify block, console or others scripts cannot access to it.
I've tried global, but It's accessible from window / console.

EDIT: no answers? I really needs that to prevent self XSS (for eg, malicious scripts to stole user data or to send bad packets to delete his rooms ect...)

Example code:

Main.js

mycustomglobal.test  = require('blabla');
mycustomglobal.test2 = require('blablablabla');

var users = require('./users.js');

Users.js file:

console.log(mycustomglobal);
// we need to be able to get test and test2

Console / or other script

console.log(mycustomglobal)
// we need to get undefined

Upvotes: 0

Views: 1179

Answers (2)

Gokhan Kurt
Gokhan Kurt

Reputation: 8277

I think something like this would suit your needs. You need to create a module, which I prefer to name private_globals.js:

var globals={};
module.exports=globals;

In your other files, you can use this module's exported object.

var globals=require("./private_globals")
console.log(globals.privateVar1);
globals.privateVar2=10;

I can think of no other way, unless you mess with source of browserify.

Upvotes: 0

wilsonzlin
wilsonzlin

Reputation: 2230

I'm not exactly sure what you're trying to achieve (maybe post some more code), but I assume you want to do something without exposing globals? Can you use a immediately-invoked function? As long as all your code is inside the function, everything will be protected but nothing will functionally change:

(function() {
    var module = require('your_module'),
        connection = new WebSocket('server.php'),
        data = [{score: 12, name: 'test'}, {score: 40, name: 'user1'}];
    // ... Your other code
})();

If you have many scripts, you might have to wrap those in functions and then call them from your main script with the IIF, passing any arguments so that they don't leak:

js_file_1.js:

(function() {
    var private_non_global = 1234;
    // Do some stuff...
    script2(private_non_global); // Go to next script...
})();

js_file_2.js:

function script2(private_non_global_from_script1) {
    private_non_global_from_script1 === 1234;
    // Do more stuff, etc.
}

If you can change things server-side you could wrap all your code inside one huge IIF. You can't have any globals that are only accessible to your code, as anyone could open the console to access any global variable. The only way to protect variables is to encapsulate all your code.

Upvotes: 2

Related Questions