Reputation: 9864
Is there a way to prevent a function from using global variables like document
, window
, navigator
, and other declared global functions ?
EDIT1: And if I could choose which global objects that are restricted it would be great, because I would like to allow the function to use for an example the Math object and it's functions...
Upvotes: 3
Views: 737
Reputation:
Is there a way to prevent a function from using global variables like document, window, navigator, and other declared global functions?
No, unless...
The only way this task is possible is if the lexical scope of the functions can be altered -- that is, the source is modified in some way, such as wrapping it as shown below.
Imagine:
;(function () {
var window = "Hello"
// original content
function foo () {
alert(window)
}
foo()
})()
This approach is used often in libraries to create private namespaces but, in those cases, the original source is also available and designed with this in mind. I have used this with document
before to alter a local version of jQuery.
While with
might look promising at first, it is important to realize it is only a lexical construct as well and does not introduce dynamic variables.
Happy coding.
Upvotes: 5
Reputation: 14330
You could ask your users to restrict themselves to ADsafe code. From the website:
ADsafe makes it safe to put guest code (such as third party scripted advertising or widgets) on a web page. ADsafe defines a subset of JavaScript that is powerful enough to allow guest code to perform valuable interactions, while at the same time preventing malicious or accidental damage or intrusion. The ADsafe subset can be verified mechanically by tools like JSLint so that no human inspection is necessary to review guest code for safety. The ADsafe subset also enforces good coding practices, increasing the likelihood that guest code will run correctly.
If you tick the right box, JSLint will verify that code is ADsafe-compliant and therefore safe to execute on your site.
Upvotes: 0