7
7
8
8
A sandboxed JSONP implementation for the browser.
9
9
10
+ # Why
11
+
12
+ If for any reason you still have to use JSONP instead of ajax & CORS on a page with sensitive data to fetch data
13
+ from third-party services, you can use this package which makes jsonp requests more secure using a temporary sandboxed
14
+ iframe as a proxy. This could potentially protect from the XSS attack injected in the jsonp response,
15
+ since the sandbox iframe does not have unsafe access to its parent page. At the same time, json data can be sent
16
+ from iframe to the parent document as a simple json string using the window.postMessage feature.
17
+ The package supports sandbox and non-sandbox mode (like typical jsonp packages), by default
18
+ sandbox mode is preffered, but not required.
19
+
10
20
# Features
11
- - optional sandbox mechanism for safer requests to untrusted origins (internally used iframes)
12
- - support Promise and callback style
21
+ - ** optional sandbox mechanism for safer requests to untrusted origins (internally used iframes)**
22
+ - support Promise and callback styles
13
23
- support custom Promise class
14
24
- anti-caching ` _rnd ` query param
15
25
- support query params in url string and/or options.params property
16
26
- automatically encoding params, converting objects and arrays params to JSON strings
17
27
18
- ## Functional diagram
19
- Sandbox mode:
20
-
21
- ![ Sandbox functional diagram] ( https://github.com/DigitalBrainJS/safe-jsonp/raw/master/public/safe-jsonp.png )
22
-
23
28
## Try It!
24
- [ Github demo] ( http://htmlpreview.github.io/?https://github.com/DigitalBrainJS/safe-jsonp/blob/master/public/index.html )
25
-
26
- [ JSFiddle.net demo] ( https://jsfiddle.net/DigitalBrain/ugz5qn0r/10/ )
29
+ [ JSFiddle.net demo] ( https://jsfiddle.net/DigitalBrain/ugz5qn0r/ )
27
30
28
31
## Installation
29
32
@@ -33,7 +36,31 @@ Install for node.js or browserify using `npm`:
33
36
$ npm install safe-jsonp --save
34
37
```
35
38
36
- ## Direct usage in the browser
39
+ ## Basic usage example
40
+ Promise style:
41
+ ``` javascript
42
+ import JSONP from " safe-jsonp" ;
43
+
44
+ JSONP (' http://api.github.com/users/DigitalBrainJS' )
45
+ .then ( data => console .log (' JSONP data object:' , data))
46
+ .catch ( err => console .warn (' Oops...we got an error' , err .message ))
47
+ ```
48
+
49
+
50
+ Callback style:
51
+ ``` javascript
52
+ import JSONP from " safe-jsonp" ;
53
+
54
+ JSONP (' http://api.github.com/users/DigitalBrainJS' , (err , data ) => {
55
+ if (err){
56
+ console .warn (' Oops...we got an error' , err .message )
57
+ }else {
58
+ console .log (' JSON data:' , data)
59
+ }
60
+ })
61
+ ```
62
+
63
+ ## CDN
37
64
Use unpkg.com cdn to get link to script/module from the package:
38
65
- UMD ES5 version (~ 15kB)
39
66
``` html
@@ -44,105 +71,54 @@ Use unpkg.com cdn to get link to script/module from the package:
44
71
<script src =" https://unpkg.com/safe-jsonp/dist/safe-jsonp.umd.min.js" ></script >
45
72
```
46
73
- ESM ES2015 module (~ 14kB)
47
- ``` html
74
+ ``` javascript
48
75
import JSONP from " https://unpkg.com/safe-jsonp/dist/safe-jsonp.esm.js"
49
76
```
50
- - minified ESM ES2015 module (~ 7kB)
51
- ``` html
52
- import JSONP from "https://unpkg.com/safe-jsonp/dist/safe-jsonp.esm.min.js"
53
- ```
54
-
55
-
56
- ## API
57
-
58
- ### JSONP(url: String, [ options: Object] ): \< Promise>
59
- ### JSONP(url: String, [ options: Object] , cb: Function): \< JSONP>
60
-
61
- - ` url: String ` url to fetch
62
- - ` [options: Object] `
63
- - ` sandbox: Boolean|Undefined= undefined ` sets sandbox mode for query handling to untrusted origins.
64
- Default ` undefined ` value means prefer sandboxed mode, but allow non-sandboxed query if the environment doesn't
65
- support it. In sandboxed mode all requests will be done in invisible iframe proxy, created temporally for each
66
- origin
67
- - ` idleTimeout: Number= 15000 ` idle timeout for each sandbox in ms
68
- - ` params: Object ` Object with query params to combine with a URL string
69
- - ` timeout: Number= 15000 ` max query pending time in ms. Default: ` 15000 ` (15 seconds)
70
- - ` preventCache: Boolean= true ` force disable cache by adding timestamp to a query param ` _rnd `
71
- - ` cbParam: String= 'callback' ` name of the query param used by backend to get the name of the JSONP callback
72
- - ` Promise: Function ` Promise class that be used instead of native (if environment supports it)
73
- - ` abortable: Boolean ` enables ability to abort for Promise mode. If this option is set to true,
74
- an additional property called abort will be created in options object.
75
- This allows to get the abort function via shared options object.
76
- - ` [cb: Function(err: ?Error, [data: Object])] ` callback function, called when jsonp query is complete
77
- (with success or error).
78
- If this argument is omitted, the function returns a Promise, otherwise, a JSONP instance will be returned.
79
-
80
- Returns a promise or JSON instance depending on the presence of a callback argument
81
-
82
- ### JSONP class instance
83
- * instance methods:*
84
- - ` abort() ` aborts the jsonp query with ` Error: aborted ` , handled by callback or Promise chain.
77
+ ## Functional diagram
78
+ Sandbox mode:
85
79
86
- * static methods:*
87
- - ` parseURL(url: String): URL|Object ` parse URL into components
88
- - ` parseParams(url: String): Object ` parse URL params string eg. ` a=1&b=2 ` to params object ` {a:1, b:2} `
89
- - ` encodeParams(params: Object): String ` encode params object to string
90
-
91
- ## Usage example
92
- Promise style:
93
- ``` javascript
94
- JSONP (' http://api.github.com/users/DigitalBrainJS' )
95
- .then ( data => console .log (' JSONP data object:' , data), err => console .warn (' Oops...we got an error' , err .message ))
96
- ```
80
+ ![ Sandbox functional diagram] ( https://github.com/DigitalBrainJS/safe-jsonp/raw/master/public/safe-jsonp.png )
97
81
82
+ ## More examples
83
+ ##### additional options:
98
84
``` javascript
99
- // in the context of the ES2015 async function
100
-
101
85
const Promise = require (" bluebird" );
102
86
87
+ // ...async function
88
+
103
89
const data = await JSONP (' http://api.github.com/users/DigitalBrainJS?name=bla&age=23' , {
104
90
params: {
105
91
foo: 1 ,
106
- bar: [1 ,2 ,3 ]// We can pass objects and arrays as a param value
92
+ bar: [1 ,2 ,3 ] // We can pass objects and arrays as a param value
107
93
},
108
94
109
95
timeout: 60000 , // 60 seconds
110
96
preventCache: true ,
111
97
cbParam: ' callback' ,
112
- Promise
98
+ Promise // custom Promise class
113
99
})
114
100
115
101
// will make request like https://api.github.com/users/DigitalBrainJS?name=bla&age=23&foo=1&bar=%5B1%2C2%2C3%5D&callback=_jsonpvqz.cb0
116
102
// callback param is randomly generated to avoid collisions
117
103
```
118
104
119
- Callback style:
120
- ``` javascript
121
- JSONP (' http://api.github.com/users/DigitalBrainJS' , (err , data ) => {
122
- if (err){
123
- console .warn (' Oops...we got an error' , err .message )
124
- }else {
125
- console .log (' JSON data:' , data)
126
- }
127
- })
128
- ```
129
105
130
- Accept sandbox mode only
106
+ ##### Force sandbox mode:
131
107
``` javascript
132
108
JSONP (' http://api.github.com/users/DigitalBrainJS' , {sandbox: true })
133
109
.then (data => console .log (data), err => console .warn (err))
134
-
110
+ // will fail if the browser doesn't support sandbox mode or data/blob uri for iframe
135
111
```
136
112
137
- Aborting the request:
113
+ ##### Aborting the request:
138
114
``` javascript
139
115
const jsonp = JSONP (' http://api.github.com/users/DigitalBrainJS' , (err , data ) => {
140
116
console .log (err) // Error: aborted
141
117
});
142
118
143
119
jsonp .abort ();
144
120
```
145
- Or
121
+ Or when using Promise:
146
122
``` javascript
147
123
const sharedOptions = {abortable: true };
148
124
@@ -152,6 +128,41 @@ JSONP('http://api.github.com/users/DigitalBrainJS', sharedOptions)
152
128
sharedOptions .abort ();
153
129
```
154
130
131
+ ## API
132
+
133
+ ### JSONP(url: String, [ options: Object] ): \< Promise>
134
+ ### JSONP(url: String, [ options: Object] , cb: Function): \< JSONP>
135
+
136
+ - ` url: String ` url to fetch
137
+ - ` [options: Object] `
138
+ - ` sandbox: Boolean|Undefined= undefined ` sets sandbox mode for query handling to untrusted origins.
139
+ Default ` undefined ` value means prefer sandboxed mode, but allow non-sandboxed query if the environment doesn't
140
+ support it. In sandboxed mode all requests will be done in invisible iframe proxy, created temporally for each
141
+ origin
142
+ - ` idleTimeout: Number= 15000 ` idle timeout for each sandbox in ms
143
+ - ` params: Object ` Object with query params to combine with a URL string
144
+ - ` timeout: Number= 15000 ` max query pending time in ms. Default: ` 15000 ` (15 seconds)
145
+ - ` preventCache: Boolean= true ` force disable cache by adding timestamp to a query param ` _rnd `
146
+ - ` cbParam: String= 'callback' ` name of the query param used by backend to get the name of the JSONP callback
147
+ - ` Promise: Function ` Promise class that be used instead of native (if environment supports it)
148
+ - ` abortable: Boolean ` enables ability to abort for Promise mode. If this option is set to true,
149
+ an additional property called abort will be created in options object.
150
+ This allows to get the abort function via shared options object.
151
+ - ` [cb: Function(err: ?Error, [data: Object])] ` callback function, called when jsonp query is complete
152
+ (with success or error).
153
+ If this argument is omitted, the function returns a Promise, otherwise, a JSONP instance will be returned.
154
+
155
+ Returns a promise or JSON instance depending on the presence of a callback argument
156
+
157
+ ### JSONP class instance
158
+ * instance methods:*
159
+ - ` abort() ` aborts the jsonp query with ` Error: aborted ` , handled by callback or Promise chain.
160
+
161
+ * static methods:*
162
+ - ` parseURL(url: String): URL|Object ` parse URL into components
163
+ - ` parseParams(url: String): Object ` parse URL params string eg. ` a=1&b=2 ` to params object ` {a:1, b:2} `
164
+ - ` encodeParams(params: Object): String ` encode params object to string
165
+
155
166
## License
156
167
157
168
The MIT License (MIT)
0 commit comments