Debian Codegraph @

tests/android/webview/js/lib/dom_json.js

raw
1 /**
2 * domJSON.js: A simple framework for converting DOM nodes to special JSON objects, and vice versa
3 *
4 * @fileOverview
5 * @author Alex Zaslavsky
6 * @version 0.1.2
7 * @license The MIT License: Copyright (c) 2013 Alex Zaslavsky
8 */
9
10
11
12 //Load the library
13 ;(function(root, factory) {
14 /* istanbul ignore next */
15 if (typeof define === 'function' && define.amd) { //AMD
16 define(function(){
17 return factory(root);
18 });
19 } else if (typeof exports !== 'undefined') { //CommonJS/node.js
20 var domJSON = factory(root);
21 if (typeof module !== 'undefined' && module.exports) {
22 module.exports = domJSON;
23 }
24 exports = domJSON;
25 } else { //Browser global
26 window.pywebview.domJSON = factory(root);
27 }
28 })(this, function(win){
29 "use strict";
30
31 /**
32 * domJSON is a global variable to store two methods: `.toJSON()` to convert a DOM Node into a JSON object, and `.toDOM()` to turn that JSON object back into a DOM Node
33 * @namespace domJSON
34 * @global
35 */
36 var domJSON = {};
37
38
39
40 /**
41 * An object specifying a list of fields and how to filter it, or an array with the first value being an optional boolean to convey the same information
42 * @typedef {Object|Array} FilterList
43 * @property {boolean} [exclude=false] If this is set to `true`, the `filter` property will specify which fields to exclude from the result (boolean difference), not which ones to include (boolean intersection)
44 * @property {string[]} values An array of strings which specify the fields to include/exclude from some broader list
45 */
46
47
48
49 /**
50 * Default metadata for a JSON object
51 * @private
52 * @ignore
53 */
54 var metadata = {
55 href: win.location.href || null,
56 userAgent: window.navigator && window.navigator.userAgent ? window.navigator.userAgent : null,
57 version: '0.1.2'
58 };
59
60
61
62 /**
63 * Default options for creating the JSON object
64 * @private
65 * @ignore
66 */
67 var defaultsForToJSON = {
68 absolutePaths: ['action', 'data', 'href', 'src'],
69 //absStylePaths: ['attr', 'background', 'background-image', 'border-image', 'border-image-source', 'content', 'list-style-image', 'mask-image'], //http://stackoverflow.com/questions/27790925/what-are-all-the-css3-properties-that-accept-urls-or-uris
70 attributes: true,
71 computedStyle: false,
72 cull: true,
73 deep: true,
74 domProperties: true,
75 filter: false,
76 htmlOnly: false,
77 metadata: true,
78 //parse: false,
79 serialProperties: false,
80 stringify: false,
81 allowDangerousElements: false
82 };
83
84
85
86 /**
87 * Default options for creating a DOM node from a previously generated domJSON object
88 * @private
89 * @ignore
90 */
91 var defaultsForToDOM = {
92 noMeta: false,
93 allowDangerousElements: false
94 };
95
96
97
98 /**
99 * A list of disallowed HTMLElement tags - there is no flexibility here, these cannot be processed by domJSON for security reasons!
100 * @private
101 * @ignore
102 */
103 var banned = [
104 'link',
105 'script'
106 ]; //Consider (maybe) adding the following tags: iframe, html, audio, video, object
107
108
109
110 /**
111 * A list of node properties that must be copied if they exist; there is no user option that will remove these
112 * @private
113 * @ignore
114 */
115 var required = [
116 'nodeType',
117 'nodeValue',
118 'tagName'
119 ];
120
121
122
123 /**
124 * A list of node properties to specifically avoid simply copying; there is no user option that will allow these to be copied directly
125 * @private
126 * @ignore
127 */
128 var ignored = [
129 'attributes',
130 'childNodes',
131 'children',
132 'classList',
133 'dataset',
134 'style'
135 ];
136
137
138
139 /**
140 * A list of serialized read-only nodes to ignore; these can overwritten if the user specifies the "filter" option
141 * @private
142 * @ignore
143 */
144 var serials = [
145 'innerHTML',
146 'innerText',
147 'outerHTML',
148 'outerText',
149 'prefix',
150 'text',
151 'textContent',
152 'wholeText'
153 ];
154
155
156
157 /**
158 * Utility function to extend an object - useful for synchronizing user-submitted options with default values; same API as underscore extend
159 * @param {Object} [target] The object that will be extended
160 * @param {...Object} [added] Additional objects that will extend the target
161 * @private
162 * @ignore
163 */
164 var extend = function(target) {
165 if (!arguments.length) {
166 return arguments[0] || {};
167 }
168
169 //Overwrite matching properties on the target from the added object
170 for (var p in arguments[1]) {
171 target[p] = arguments[1][p];
172 }
173
174 //If we have more arguments, run the function recursively
175 if (arguments.length > 2) {
176 var moreArgs = [target].concat(Array.prototype.slice.call(arguments, 2));
177 return extend.apply( null, moreArgs);
178 } else {
179 return target;
180 }
181 };
182
183
184
185 /**
186 * Get all of the unique values (in the order they first appeared) from one or more arrays
187 * @param {...Array} constituent An array to combine into a larger array of unique values
188 * @private
189 * @ignore
190 */
191 var unique = function() {
192 if (!arguments.length) {
193 return [];
194 }
195
196 var all = Array.prototype.concat.apply([], arguments);
197 for (var a = 0; a < all.length; a++) {
198 if (all.indexOf(all[a]) < a) {
199 all.splice(a, 1);
200 a--;
201 }
202 }
203 return all;
204 };
205
206
207 /**
208 * Make a shallow copy of an object or array
209 * @param {Object|string[]} item The object/array that will be copied
210 * @private
211 * @ignore
212 */
213 var copy = function(item) {
214 if (item instanceof Array) {
215 return item.slice();
216 } else {
217 var output = {};
218 for (var i in item) {
219 output[i] = item[i];
220 }
221 return output;
222 }
223 };
224
225
226
227 /**
228 * Do a boolean intersection between an array/object and a filter array
229 * @param {Object|string[]} item The object/array that will be intersected with the filter
230 * @param {boolean|string[]} filter Specifies which properties to select from the "item" (or element to keep, if "item is an array")
231 * @private
232 * @ignore
233 */
234 var boolInter = function(item, filter) {
235 var output;
236 if (item instanceof Array) {
237 output = unique(item.filter(function(val) { return filter.indexOf(val) > -1; }));
238 } else {
239 output = {};
240 for (var f in filter) {
241 if (item.hasOwnProperty(filter[f])) {
242 output[filter[f]] = item[filter[f]];
243 }
244 }
245 }
246 return output;
247 };
248
249
250
251 /**
252 * Do a boolean difference between an array/object and a filter array
253 * @param {Object|string[]} item The object/array that will be differentiated with the filter
254 * @param {boolean|string[]} filter Specifies which properties to exclude from the "item" (or element to remove, if "item is an array")
255 * @private
256 * @ignore
257 */
258 var boolDiff = function(item, filter) {
259 var output;
260 if (item instanceof Array) {
261 output = unique(item.filter(function(val) { return filter.indexOf(val) === -1; }));
262 } else {
263 output = {};
264 for (var i in item) {
265 output[i] = item[i];
266 }
267 for (var f in filter) {
268 if (output.hasOwnProperty(filter[f])) {
269 delete output[filter[f]];
270 }
271 }
272 }
273 return output;
274 };
275
276
277
278 /**
279 * Determine whether we want to do a boolean intersection or difference
280 * @param {Object|string[]} item The object/array that will be differentiated with the filter
281 * @param {boolean|Array} filter Specifies which a filter behavior; if it is an array, the first value can be a boolean, indicating whether the filter array is intended for differentiation (true) or intersection (false)
282 * @private
283 * @ignore
284 */
285 var boolFilter = function(item, filter) {
286 //A "false" filter means we return an empty copy of item
287 if (filter === false){
288 return (item instanceof Array) ? [] : {};
289 }
290
291 if (filter instanceof Array && filter.length) {
292 if (typeof filter[0] === 'boolean') {
293 if (filter.length == 1 && typeof(filter[0]) === 'boolean') {
294 //There is a filter array, but its only a single boolean
295 if (filter[0] === true) {
296 return copy(item);
297 } else {
298 return (item instanceof Array) ? [] : {};
299 }
300 } else {
301 //The filter operation has been set explicitly; true = difference
302 if (filter[0] === true) {
303 return boolDiff(item, filter.slice(1));
304 } else {
305 return boolInter(item, filter.slice(1));
306 }
307 }
308 } else {
309 //There is no explicit operation on the filter, meaning it defaults to an intersection
310 return boolInter(item, filter);
311 }
312 } else {
313 return copy(item);
314 }
315 };
316
317
318
319 /**
320 * Ensure that a FilterList type input is converted into its shorthand array form
321 * @param {boolean|FilterList} filterList The FilterList, or boolean, that will converted into the shorthand form
322 * @private
323 * @ignore
324 */
325 var toShorthand = function(filterList) {
326 var outputArray;
327 if (typeof filterList === 'boolean') {
328 return filterList;
329 } else if (typeof filterList === 'object' && filterList !== null) {
330 if (filterList instanceof Array) {
331 return filterList.filter(function(v, i){
332 return typeof v === 'string' || (i === 0 && v === true) ? true : false;
333 });
334 } else {
335 if (!(filterList.values instanceof Array)) {
336 return false;
337 }
338
339 outputArray = filterList.values.filter(function(v){
340 return typeof v === 'string' ? true : false;
341 });
342
343 if (!outputArray.length) {
344 return false;
345 }
346
347 if (filterList.exclude) {
348 outputArray.unshift(filterList.exclude);
349 }
350 return outputArray;
351 }
352 } else if (filterList) {
353 return true;
354 }
355 return false;
356 };
357
358
359
360 /**
361 * Check if the supplied string value is a relative path, and convert it to an absolute one if necessary; the segment processing paths leading with "../" was inspired by: http://stackoverflow.com/a/14780463/2230156
362 * @param {string} value The value that might be a relative path, and would thus need conversion
363 * @param {Object} origin The origin URL from which to which non-absolute paths are relative
364 * @private
365 * @ignore
366 */
367 var toAbsolute = function(value, origin) {
368 var protocol, stack, parts;
369 //Sometimes, we get lucky and the DOM Node we're working on already has the absolute URL as a DOM property, so we can just use that
370 /*if (node[name]){
371 //We can just grab the compiled URL directly from the DOM element - easy peasy
372 var sub = node[name].indexOf(value);
373 if (sub !== -1) {
374 return node[name];
375 }
376 }*/
377
378 //Check to make sure we don't already have an absolute path, or even a dataURI
379 if ( value.match(/(?:^data\:|^[\w\-\+\.]*?\:\/\/|^\/\/)/i) ){
380 return value;
381 }
382
383 //If we are using the root URL, start from there
384 if ( value.charAt(0) === '/' ){
385 return origin + value.substr(1);
386 }
387
388 //Uh-oh, the relative path is leading with a single or double dot ("./" or "../"); things get a bit harder...
389 protocol = origin.indexOf('://') > -1 ? origin.substring(0, origin.indexOf('://') + 3) : '';
390 stack = (protocol.length ? origin.substring(protocol.length) : origin).split('/');
391 parts = value.split('/');
392
393 //The value after the last slash is ALWAYS considered a filename, not a directory, so always have trailing slashes on paths ending at directories!
394 stack.pop();
395
396 //Cycle through the relative path, changing the stack as we go
397 for (var i=0; i<parts.length; i++) {
398 if (parts[i] == '.') {
399 continue;
400 }
401 if (parts[i] == '..') {
402 if (stack.length > 1) {
403 stack.pop();
404 }
405 } else {
406 stack.push(parts[i]);
407 }
408 }
409 return (protocol + stack.join('/'));
410 };
411
412
413
414 /**
415 * Create a copy of a node's properties, ignoring nasty things like event handles and functions
416 * @param {Node} node The DOM Node whose properties will be copied
417 * @param {Object} [opts] The options object passed down from the .toJSON() method; includes all options, even those not relevant to this function
418 * @private
419 * @ignore
420 */
421 var copyJSON = function(node, opts) {
422 var copy = {};
423 //Copy all of the node's properties
424 for (var n in node){
425 //Make sure this property can be accessed
426 try {
427 //accessing `selectionDirection`, `selectionStart`, or `selectionEnd` throws in WebKit-based browsers
428 node[n];
429 } catch (e) {
430 continue;
431 }
432 //Make sure this is an own property, and isn't a live javascript function for security reasons
433 if (typeof node[n] !== 'undefined' && typeof node[n] !== 'function' && n.charAt(0).toLowerCase() === n.charAt(0)) {
434 //Only allowed objects are arrays
435 if ( typeof node[n] !== 'object' || node[n] instanceof Array ) {
436 //If we are eliminating empty fields, make sure this value is not NULL or UNDEFINED
437 if (opts.cull) {
438 if (node[n] || node[n] === 0 || node[n] === false) {
439 copy[n] = node[n];
440 }
441 } else {
442 copy[n] = node[n];
443 }
444 }
445 }
446 }
447
448 copy = boolFilter(copy, opts.domProperties);
449 return copy;
450 };
451
452
453
454 /**
455 * Convert the attributes property of a DOM Node to a JSON ready object
456 * @param {Node} node The DOM Node whose attributes will be copied
457 * @param {Object} [opts] The options object passed down from the .toJSON() method; includes all options, even those not relevant to this function
458 * @private
459 * @ignore
460 */
461 var attrJSON = function(node, opts) {
462 var attributes = {};
463 var attr = node.attributes;
464 var length = attr.length;
465 var absAttr;
466
467 for (var i = 0; i < length; i++) {
468 attributes[attr[i].name] = attr[i].value;
469 }
470 attributes = opts.attributes ? boolFilter(attributes, opts.attributes) : null;
471
472 //Add the attributes object, converting any specified absolute paths along the way
473 absAttr = boolFilter(attributes, opts.absolutePaths);
474 for (var i in absAttr) {
475 attributes[i] = toAbsolute(absAttr[i], opts.absoluteBase);
476 }
477
478 return attributes;
479 };
480
481
482
483 /**
484 * Grab a DOM Node's computed style
485 * @param {Node} node The DOM Node whose computed style will be calculated
486 * @param {Object} [opts] The options object passed down from the .toJSON() method; includes all options, even those not relevant to this function
487 * @private
488 * @ignore
489 */
490 var styleJSON = function(node, opts) {
491 //Grab the computed style
492 var style, css = {};
493 if (opts.computedStyle && node.style instanceof CSSStyleDeclaration) {
494 style = win.getComputedStyle(node);
495 } else {
496 return null;
497 }
498
499 //Get the relevant properties from the computed style
500 for (var k in style) {
501 if ( k !== 'cssText' && !k.match(/\d/) && typeof style[k] === 'string' && style[k].length ) {
502 //css.push(k+ ': ' +style[k]+ ';');
503 css[k] = style[k];
504 }
505 }
506
507 //Filter the style object
508 return (opts.computedStyle instanceof Array) ? boolFilter(css, opts.computedStyle) : css;
509 };
510
511
512
513 /**
514 * Convert a single DOM Node into a simple object
515 * @param {Node} node The DOM Node that will be converted
516 * @param {Object} [opts] The options object passed down from the .toJSON() method; includes all options, even those not relevant to this function
517 * @private
518 * @ignore
519 */
520 var toJSON = function(node, opts, depth) {
521 var style, kids, kidCount, thisChild, children, copy = copyJSON(node, opts);
522
523 //Per default, some tags are not allowed
524 if (node.nodeType === 1) {
525 if (!opts.allowDangerousElements) {
526 for (var b in banned) {
527 if (node.tagName.toLowerCase() === banned[b]) {
528 return null;
529 }
530 }
531 }
532 } else if (node.nodeType === 3 && !node.nodeValue.trim()) {
533 //Ignore empty buffer text nodes
534 return null;
535 }
536
537 //Copy all attributes and styles, if allowed
538 if (opts.attributes && node.attributes) {
539 copy.attributes = attrJSON(node, opts);
540 }
541 if (opts.computedStyle && (style = styleJSON(node, opts))) {
542 copy.style = style;
543 }
544
545 //Should we continue iterating?
546 if (opts.deep === true || (typeof opts.deep === 'number' && opts.deep > depth)) {
547 //We should!
548 children = [];
549 kids = (opts.htmlOnly) ? node.children : node.childNodes;
550 kidCount = kids.length;
551 for (var c = 0; c < kidCount; c++) {
552 thisChild = toJSON(kids[c], opts, depth + 1);
553 if (thisChild) {
554 children.push(thisChild);
555 }
556 }
557
558 //Append the children in the appropriate place
559 copy.childNodes = children;
560 }
561 return copy;
562 };
563
564
565
566 /**
567 * Take a DOM node and convert it to simple object literal (or JSON string) with no circular references and no functions or events
568 * @param {Node} node The actual DOM Node which will be the starting point for parsing the DOM Tree
569 * @param {Object} [opts] A list of all method options
570 * @param {boolean} [opts.allowDangerousElements=`false`] Use `true` to parse the potentially dangerous elements `<link>` and `<script>`
571 * @param {boolean|FilterList} [opts.absolutePaths=`'action', 'data', 'href', 'src'`] Only relevant if `opts.attributes` is not `false`; use `true` to convert all relative paths found in attribute values to absolute paths, or specify a `FilterList` of keys to boolean search
572 * @param {boolean|FilterList} [opts.attributes=`true`] Use `true` to copy all attribute key-value pairs, or specify a `FilterList` of keys to boolean search
573 * @param {boolean|FilterList} [opts.computedStyle=`false`] Use `true` to parse the results of "window.getComputedStyle()" on every node (specify a `FilterList` of CSS properties to be included via boolean search); this operation is VERY costly performance-wise!
574 * @param {boolean} [opts.cull=`false`] Use `true` to ignore empty element properties
575 * @param {boolean|number} [opts.deep=`true`] Use `true` to iterate and copy all childNodes, or an INTEGER indicating how many levels down the DOM tree to iterate
576 * @param {boolean|FilterList} [opts.domProperties=true] 'false' means only 'tagName', 'nodeType', and 'nodeValue' properties will be copied, while a `FilterList` can specify DOM properties to include or exclude in the output (except for ones which serialize the DOM Node, which are handled separately by `opts.serialProperties`)
577 * @param {boolean} [opts.htmlOnly=`false`] Use `true` to only iterate through childNodes where nodeType = 1 (aka, instances of HTMLElement); irrelevant if `opts.deep` is `true`
578 * @param {boolean} [opts.metadata=`false`] Output a special object of the domJSON class, which includes metadata about this operation
579 * @todo {boolean|FilterList} [opts.parse=`false`] a `FilterList` of properties that are DOM nodes, but will still be copied **PLANNED**
580 * @param {boolean|FilterList} [opts.serialProperties=`true`] Use `true` to ignore the properties that store a serialized version of this DOM Node (ex: outerHTML, innerText, etc), or specify a `FilterList` of serial properties (no boolean search!)
581 * @param {boolean} [opts.stringify=`false`] Output a JSON string, or just a JSON-ready javascript object?
582 * @return {Object|string} A JSON-friendly object, or JSON string, of the DOM node -> JSON conversion output
583 * @method
584 * @memberof domJSON
585 */
586 domJSON.toJSON = function(node, opts) {
587 var copy, keys = [], options = {}, output = {};
588 var timer = new Date().getTime();
589 var requiring = required.slice();
590 var ignoring = ignored.slice();
591
592 //Update the default options w/ the user's custom settings
593 options = extend({}, defaultsForToJSON, opts);
594
595 //Convert all options that accept FilterList type inputs into the shorthand notation
596 options.absolutePaths = toShorthand(options.absolutePaths);
597 options.attributes = toShorthand(options.attributes);
598 options.computedStyle = toShorthand(options.computedStyle);
599 options.domProperties = toShorthand(options.domProperties);
600 options.serialProperties = toShorthand(options.serialProperties);
601
602 //Make sure there is a base URL for absolute path conversions
603 options.absoluteBase = win.location.origin + '/';
604
605 //Make lists of which DOM properties to skip and/or which are absolutely necessary
606 if (options.serialProperties !== true) {
607 if (options.serialProperties instanceof Array && options.serialProperties.length) {
608 if (options.serialProperties[0] === true) {
609 ignoring = ignoring.concat( boolDiff(serials, options.serialProperties) );
610 } else {
611 ignoring = ignoring.concat( boolInter(serials, options.serialProperties) );
612 }
613 } else {
614 ignoring = ignoring.concat( serials );
615 }
616 }
617 if (options.domProperties instanceof Array) {
618 if (options.domProperties[0] === true) {
619 options.domProperties = boolDiff( unique(options.domProperties, ignoring), requiring );
620 } else {
621 options.domProperties = boolDiff( unique(options.domProperties, requiring), ignoring );
622 }
623 } else {
624 if (options.domProperties === false) {
625 options.domProperties = requiring;
626 } else {
627 options.domProperties = [true].concat(ignoring);
628 }
629 }
630
631 //Transform the node into an object literal
632 copy = toJSON(node, options, 0);
633
634 //Wrap our copy object in a nice object of its own to save some metadata
635 if (options.metadata) {
636 output.meta = extend({}, metadata, {
637 clock: new Date().getTime() - timer,
638 date: new Date().toISOString(),
639 dimensions: {
640 inner: {
641 x: window.innerWidth,
642 y: window.innerHeight
643 },
644 outer: {
645 x: window.outerWidth,
646 y: window.outerHeight
647 }
648 },
649 options: options
650 });
651 output.node = copy;
652 } else {
653 output = copy;
654 }
655
656 //If opts.stringify is true, turn the output object into a JSON string
657 if (options.stringify) {
658 return JSON.stringify(output);
659 }
660 return output;
661 };
662
663
664
665 /**
666 * Create a node based on a given nodeType
667 * @param {number} type The type of DOM Node (only the integers 1, 3, 7, 8, 9, 10, 11 are valid, see https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType); currently, only nodeTypes 1,3, and 11 have been tested and are officially supported
668 * @param {DocumentFragment} doc The document fragment to which this newly created DOM Node will be added
669 * @param {Object} data The saved DOM properties that are part of the JSON representation of this DOM Node
670 * @private
671 * @ignore
672 */
673 var createNode = function(type, doc, data) {
674 if (doc instanceof DocumentFragment) {
675 doc = doc.ownerDocument;
676 }
677 switch(type) {
678 case 1: //HTMLElement
679 if (typeof data.tagName === 'string') {
680 return doc.createElement(data.tagName);
681 }
682 return false;
683
684 case 3: //Text Node
685 if (typeof data.nodeValue === 'string' && data.nodeValue.length) {
686 return doc.createTextNode(data.nodeValue);
687 }
688 return doc.createTextNode('');
689
690 case 7: //Processing Instruction
691 if (data.hasOwnProperty('target') && data.hasOwnProperty('data')) {
692 return doc.createProcessingInstruction(data.target, data.data);
693 }
694 return false;
695
696 case 8: //Comment Node
697 if (typeof data.nodeValue === 'string') {
698 return doc.createComment(data.nodeValue);
699 }
700 return doc.createComment('');
701
702 case 9: //HTML Document
703 return doc.implementation.createHTMLDocument(data);
704
705 case 11: //Document Fragment
706 return doc;
707
708 default: //Failed
709 return false;
710 }
711 };
712
713
714
715 //Recursively convert a JSON object generated by domJSON to a DOM Node
716 /**
717 * Do the work of converting a JSON object/string generated by domJSON to a DOM Node
718 * @param {Object} obj The JSON representation of the DOM Node we are about to create
719 * @param {HTMLElement} parent The HTML Element to which this DOM Node will be appended
720 * @param {DocumentFragment} doc The document fragment to which this newly created DOM Node will be added
721 * @param {Object} [opts] A list of all method options
722 * @private
723 * @ignore
724 */
725 var toDOM = function(obj, parent, doc, opts) {
726 //Create the node, if possible
727 if (obj.nodeType) {
728 //Per default, some tags are not allowed
729 if (obj.nodeType === 1 && !opts.allowDangerousElements) {
730 for (var b in banned) {
731 if (obj.tagName.toLowerCase() === banned[b]) {
732 return false;
733 }
734 }
735 }
736 var node = createNode(obj.nodeType, doc, obj);
737 parent.appendChild(node);
738 } else {
739 return false;
740 }
741
742 //Copy all available properties that are not arrays or objects
743 for (var x in obj) {
744 if (typeof obj[x] !== 'object' && x !== 'isContentEditable' && x !== 'childNodes') {
745 try {
746 node[x] = obj[x];
747 } catch(e) {
748 continue;
749 }
750 }
751 }
752
753 //If this is an HTMLElement, set the attributes
754 var src;
755 if (obj.nodeType === 1 && obj.tagName) {
756 if (obj.attributes) {
757 //Check for cross-origin
758 /*src = obj.attributes.src ? 'src' : (obj.attributes.href ? 'href' : null);
759 if (src) {
760 obj.attributes[src] += ( (obj.attributes[src].indexOf('?') === -1) ? '?' : '&'+Math.random().toString(36).slice(-2)+'=' ) + Math.random().toString(36).slice(-4);
761 obj.attributes.crossorigin = 'anonymous';
762 //node.setAttribute('crossorigin', 'anonymous');
763 }*/
764 for (var a in obj.attributes) {
765 node.setAttribute(a, obj.attributes[a]);
766 }
767 }
768 }
769
770 //Finally, if we have childNodes, recurse through them
771 if (obj.childNodes && obj.childNodes.length) {
772 for (var c in obj.childNodes) {
773 toDOM(obj.childNodes[c], node, doc, opts);
774 }
775 }
776 };
777
778
779
780 /**
781 * Take the JSON-friendly object created by the `.toJSON()` method and rebuild it back into a DOM Node
782 * @param {Object} obj A JSON friendly object, or even JSON string, of some DOM Node
783 * @param {Object} [opts] A list of all method options
784 * @param {boolean} [opts.allowDangerousElements=`false`] Use `true` to include the potentially dangerous elements `<link>` and `<script>`
785 * @param {boolean} [opts.noMeta=`false`] `true` means that this object is not wrapped in metadata, which it makes it somewhat more difficult to rebuild properly...
786 * @return {DocumentFragment} A `DocumentFragment` (nodeType 11) containing the result of unpacking the input `obj`
787 * @method
788 * @memberof domJSON
789 */
790 domJSON.toDOM = function(obj, opts) {
791 var options, node;
792 //Parse the JSON string if necessary
793 if (typeof obj === 'string') {
794 obj = JSON.parse(obj);
795 }
796 //Update the default options w/ the user's custom settings
797 options = extend({}, defaultsForToDOM, opts);
798
799 //Create a document fragment, and away we go!
800 node = document.createDocumentFragment();
801 if (options.noMeta) {
802 toDOM(obj, node, node, options);
803 } else {
804 toDOM(obj.node, node, node, options);
805 }
806 return node;
807 };
808
809
810
811 /* test-code */
812 //The code below is only included for private API testing, and needs to be removed in distributed builds
813 domJSON.__extend = extend;
814 domJSON.__unique = unique;
815 domJSON.__copy = copy;
816 domJSON.__boolFilter = boolFilter;
817 domJSON.__boolInter = boolInter;
818 domJSON.__boolDiff = boolDiff;
819 domJSON.__toShorthand = toShorthand;
820 /* end-test-code */
821
822 return domJSON;
823 });