-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
60 lines (55 loc) · 2.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
module.exports = function(opts) {
return new IFrame(opts)
}
function IFrame(opts) {
if (!opts) opts = {}
this.opts = opts
this.container = opts.container || document.body
this.setHTML(opts)
}
IFrame.prototype.parseHTMLOptions = function(opts) {
if (typeof opts === 'string') opts = {html: opts}
if (!opts) opts = {}
if (opts.body || opts.head) {
if (!opts.body) opts.body = ""
if (!opts.head) opts.head = ""
opts.html = '<!DOCTYPE html><html><head>' + opts.head + '</head><body>' + opts.body + '</body></html>'
}
if (!opts.sandboxAttributes) opts.sandboxAttributes = ['allow-scripts']
return opts
}
IFrame.prototype.remove = function() {
if (this.iframe) this.container.removeChild(this.iframe)
}
IFrame.prototype.setHTML = function(opts) {
opts = this.parseHTMLOptions(opts)
if (!opts.html && !opts.src) return
this.remove()
// if src is passed in use that (this mode ignores body/head/html options)
if (opts.src) {
var targetUrl = opts.src
} else {
// create a blob for opts.html and set as iframe `src` attribute
var blob = new Blob([opts.html], { encoding: 'UTF-8', type: 'text/html' })
var U = typeof URL !== 'undefined' ? URL : webkitURL
var targetUrl = U.createObjectURL(blob)
}
// create temporary iframe for generating HTML string
// element is inserted into the DOM as a string so that the security policies do not interfere
// see: https://gist.github.com/kumavis/8202447
var tempIframe = document.createElement('iframe')
tempIframe.src = targetUrl
tempIframe.setAttribute('scrolling', this.opts.scrollingDisabled ? 'no' : 'yes')
tempIframe.style.width = '100%'
tempIframe.style.height = '100%'
tempIframe.style.border = '0'
tempIframe.sandbox = opts.sandboxAttributes.join(' ')
if (opts.name) tempIframe.setAttribute('name', opts.name)
// generate HTML string
var htmlSrc = tempIframe.outerHTML
// insert HTML into container
this.container.insertAdjacentHTML('beforeend', htmlSrc)
// retrieve created iframe from DOM
var neighborIframes = this.container.querySelectorAll('iframe')
this.iframe = neighborIframes[neighborIframes.length-1]
}