Skip to content

Instantly share code, notes, and snippets.

@Havvy
Last active December 16, 2015 04:09
Show Gist options
  • Save Havvy/5375601 to your computer and use it in GitHub Desktop.
Save Havvy/5375601 to your computer and use it in GitHub Desktop.
Silly Proposal: Addition of the 'with' attribute to the <script> tag.
With 'with' attribute defines the global context for the script to run in.
The 'with' attribute defaults to the current global context, or `window` if in
the original HTML. By defaulting to the current global context, a script can't
create a new script that gains access to data outside of its context.
In scripts with the `with` attribute set, they shall run in ES5/strict mode.
Using `var` in the top level works as you would expect, setting values on the
context object for the script. If a script doesn't want to do that, the script
can use `let` instead.
For example, let's take the following page:
```example-mashup.html
<html>
<head>
<meta charset="utf-8">
<script>window.MYGLOBAL = {window: window};</script>
<title>An example page</title>
</head>
<body>
</body>
<script src="/scripts/initialization.js" with='MYGLOBAL'></script>
<script src="http://insecure.website.com/mashup.js" with='MYGLOBAL.mashupContext'></script>
</html>
```
Where /scripts/initalization.js looks like this:
```/scripts/initialization.js
// ...
var SomeConstructor = function () {
// ...
}
// ...
var mashupContext = (function () {
return {
// ...
}
}());
// ...
```
The end result for executing that script, ignoring the unshown code, would be
that window.MYGLOBAL has the properties `SomeConstructor` and `mashupContext`,
along with `window` from the script in the head tag.
Let's say that http://insecure.website.com/mashup.js was written with with.js
in mind. It expects that the context it runs in has a few methods.
```http://insecure.website.com/mashup.js
var request = function () {
// ...
};
var parseResult = function () {
// ...
};
var init = function () {
request('/mashup/information', settings, element, function (res, err) {
if (err) return;
callback(parseResult(res));
});
};
```
In this script, it expects that `settings`, `element`, and `callback` are all
in the context of the object.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment