How to use iframe method in chromy

Best JavaScript code snippet using chromy

io-upload-iframe-coverage.js

Source:io-upload-iframe-coverage.js Github

copy

Full Screen

1/*2YUI 3.7.3 (build 5687)3Copyright 2012 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7if (typeof _yuitest_coverage == "undefined"){8 _yuitest_coverage = {};9 _yuitest_coverline = function(src, line){10 var coverage = _yuitest_coverage[src];11 if (!coverage.lines[line]){12 coverage.calledLines++;13 }14 coverage.lines[line]++;15 };16 _yuitest_coverfunc = function(src, name, line){17 var coverage = _yuitest_coverage[src],18 funcId = name + ":" + line;19 if (!coverage.functions[funcId]){20 coverage.calledFunctions++;21 }22 coverage.functions[funcId]++;23 };24}25_yuitest_coverage["build/io-upload-iframe/io-upload-iframe.js"] = {26 lines: {},27 functions: {},28 coveredLines: 0,29 calledLines: 0,30 coveredFunctions: 0,31 calledFunctions: 0,32 path: "build/io-upload-iframe/io-upload-iframe.js",33 code: []34};35_yuitest_coverage["build/io-upload-iframe/io-upload-iframe.js"].code=["YUI.add('io-upload-iframe', function (Y, NAME) {","","/**","Extends the IO to enable file uploads, with HTML forms","using an iframe as the transport medium.","@module io","@submodule io-upload-iframe","@for IO","**/","","var w = Y.config.win,"," d = Y.config.doc,"," _std = (d.documentMode && d.documentMode >= 8),"," _d = decodeURIComponent,"," _end = Y.IO.prototype.end;","","/**"," * Creates the iframe transported used in file upload"," * transactions, and binds the response event handler."," *"," * @method _cFrame"," * @private"," * @param {Object} o Transaction object generated by _create()."," * @param {Object} c Configuration object passed to YUI.io()."," * @param {Object} io"," */","function _cFrame(o, c, io) {"," var i = Y.Node.create('<iframe src=\"#\" id=\"io_iframe' + o.id + '\" name=\"io_iframe' + o.id + '\" />');"," i._node.style.position = 'absolute';"," i._node.style.top = '-1000px';"," i._node.style.left = '-1000px';"," Y.one('body').appendChild(i);"," // Bind the onload handler to the iframe to detect the file upload response."," Y.on(\"load\", function() { io._uploadComplete(o, c); }, '#io_iframe' + o.id);","}","","/**"," * Removes the iframe transport used in the file upload"," * transaction."," *"," * @method _dFrame"," * @private"," * @param {Number} id The transaction ID used in the iframe's creation."," */","function _dFrame(id) {"," Y.Event.purgeElement('#io_iframe' + id, false);"," Y.one('body').removeChild(Y.one('#io_iframe' + id));","}","","Y.mix(Y.IO.prototype, {"," /**"," * Parses the POST data object and creates hidden form elements"," * for each key-value, and appends them to the HTML form object."," * @method appendData"," * @private"," * @static"," * @param {Object} f HTML form object."," * @param {String} s The key-value POST data."," * @return {Array} o Array of created fields."," */"," _addData: function(f, s) {"," // Serialize an object into a key-value string using"," // querystring-stringify-simple."," if (Y.Lang.isObject(s)) {"," s = Y.QueryString.stringify(s);"," }",""," var o = [],"," m = s.split('='),"," i, l;",""," for (i = 0, l = m.length - 1; i < l; i++) {"," o[i] = d.createElement('input');"," o[i].type = 'hidden';"," o[i].name = _d(m[i].substring(m[i].lastIndexOf('&') + 1));"," o[i].value = (i + 1 === l) ? _d(m[i + 1]) : _d(m[i + 1].substring(0, (m[i + 1].lastIndexOf('&'))));"," f.appendChild(o[i]);"," }",""," return o;"," },",""," /**"," * Removes the custom fields created to pass additional POST"," * data, along with the HTML form fields."," * @method _removeData"," * @private"," * @static"," * @param {Object} f HTML form object."," * @param {Object} o HTML form fields created from configuration.data."," */"," _removeData: function(f, o) {"," var i, l;",""," for (i = 0, l = o.length; i < l; i++) {"," f.removeChild(o[i]);"," }"," },",""," /**"," * Sets the appropriate attributes and values to the HTML"," * form, in preparation of a file upload transaction."," * @method _setAttrs"," * @private"," * @static"," * @param {Object} f HTML form object."," * @param {Object} id The Transaction ID."," * @param {Object} uri Qualified path to transaction resource."," */"," _setAttrs: function(f, id, uri) {"," f.setAttribute('action', uri);"," f.setAttribute('method', 'POST');"," f.setAttribute('target', 'io_iframe' + id );"," f.setAttribute(Y.UA.ie && !_std ? 'encoding' : 'enctype', 'multipart/form-data');"," },",""," /**"," * Reset the HTML form attributes to their original values."," * @method _resetAttrs"," * @private"," * @static"," * @param {Object} f HTML form object."," * @param {Object} a Object of original attributes."," */"," _resetAttrs: function(f, a) {"," Y.Object.each(a, function(v, p) {"," if (v) {"," f.setAttribute(p, v);"," }"," else {"," f.removeAttribute(p);"," }"," });"," },",""," /**"," * Starts timeout count if the configuration object"," * has a defined timeout property."," *"," * @method _startUploadTimeout"," * @private"," * @static"," * @param {Object} o Transaction object generated by _create()."," * @param {Object} c Configuration object passed to YUI.io()."," */"," _startUploadTimeout: function(o, c) {"," var io = this;",""," io._timeout[o.id] = w.setTimeout("," function() {"," o.status = 0;"," o.statusText = 'timeout';"," io.complete(o, c);"," io.end(o, c);"," }, c.timeout);"," },",""," /**"," * Clears the timeout interval started by _startUploadTimeout()."," * @method _clearUploadTimeout"," * @private"," * @static"," * @param {Number} id - Transaction ID."," */"," _clearUploadTimeout: function(id) {"," var io = this;",""," w.clearTimeout(io._timeout[id]);"," delete io._timeout[id];"," },",""," /**"," * Bound to the iframe's Load event and processes"," * the response data."," * @method _uploadComplete"," * @private"," * @static"," * @param {Object} o The transaction object"," * @param {Object} c Configuration object for the transaction."," */"," _uploadComplete: function(o, c) {"," var io = this,"," d = Y.one('#io_iframe' + o.id).get('contentWindow.document'),"," b = d.one('body'),"," p;",""," if (c.timeout) {"," io._clearUploadTimeout(o.id);"," }",""," try {"," if (b) {"," // When a response Content-Type of \"text/plain\" is used, Firefox and Safari"," // will wrap the response string with <pre></pre>."," p = b.one('pre:first-child');"," o.c.responseText = p ? p.get('text') : b.get('text');"," }"," else {"," o.c.responseXML = d._node;"," }"," }"," catch (e) {"," o.e = \"upload failure\";"," }",""," io.complete(o, c);"," io.end(o, c);"," // The transaction is complete, so call _dFrame to remove"," // the event listener bound to the iframe transport, and then"," // destroy the iframe."," w.setTimeout( function() { _dFrame(o.id); }, 0);"," },",""," /**"," * Uploads HTML form data, inclusive of files/attachments,"," * using the iframe created in _create to facilitate the transaction."," * @method _upload"," * @private"," * @static"," * @param {Object} o The transaction object"," * @param {Object} uri Qualified path to transaction resource."," * @param {Object} c Configuration object for the transaction."," */"," _upload: function(o, uri, c) {"," var io = this,"," f = (typeof c.form.id === 'string') ? d.getElementById(c.form.id) : c.form.id,"," // Track original HTML form attribute values."," attr = {"," action: f.getAttribute('action'),"," target: f.getAttribute('target')"," },"," fields;",""," // Initialize the HTML form properties in case they are"," // not defined in the HTML form."," io._setAttrs(f, o.id, uri);"," if (c.data) {"," fields = io._addData(f, c.data);"," }",""," // Start polling if a callback is present and the timeout"," // property has been defined."," if (c.timeout) {"," io._startUploadTimeout(o, c);"," }",""," // Start file upload."," f.submit();"," io.start(o, c);"," if (c.data) {"," io._removeData(f, fields);"," }",""," return {"," id: o.id,"," abort: function() {"," o.status = 0;"," o.statusText = 'abort';"," if (Y.one('#io_iframe' + o.id)) {"," _dFrame(o.id);"," io.complete(o, c);"," io.end(o, c, attr);"," }"," else {"," return false;"," }"," },"," isInProgress: function() {"," return Y.one('#io_iframe' + o.id) ? true : false;"," },"," io: io"," };"," },",""," upload: function(o, uri, c) {"," _cFrame(o, c, this);"," return this._upload(o, uri, c);"," },",""," end: function(transaction, config, attr) {"," if (config && config.form && config.form.upload) {"," var io = this;"," // Restore HTML form attributes to their original values."," io._resetAttrs(f, attr);"," }",""," return _end.call(this, transaction, config);"," }","});","","","}, '3.7.3', {\"requires\": [\"io-base\", \"node-base\"]});"];36_yuitest_coverage["build/io-upload-iframe/io-upload-iframe.js"].lines = {"1":0,"11":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"34":0,"45":0,"46":0,"47":0,"50":0,"64":0,"65":0,"68":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"80":0,"93":0,"95":0,"96":0,"111":0,"112":0,"113":0,"114":0,"126":0,"127":0,"128":0,"131":0,"147":0,"149":0,"151":0,"152":0,"153":0,"154":0,"166":0,"168":0,"169":0,"182":0,"187":0,"188":0,"191":0,"192":0,"195":0,"196":0,"199":0,"203":0,"206":0,"207":0,"211":0,"225":0,"236":0,"237":0,"238":0,"243":0,"244":0,"248":0,"249":0,"250":0,"251":0,"254":0,"257":0,"258":0,"259":0,"260":0,"261":0,"262":0,"265":0,"269":0,"276":0,"277":0,"281":0,"282":0,"284":0,"287":0};37_yuitest_coverage["build/io-upload-iframe/io-upload-iframe.js"].functions = {"(anonymous 2):34":0,"_cFrame:27":0,"_dFrame:45":0,"_addData:61":0,"_removeData:92":0,"_setAttrs:110":0,"(anonymous 3):126":0,"_resetAttrs:125":0,"(anonymous 4):150":0,"_startUploadTimeout:146":0,"_clearUploadTimeout:165":0,"(anonymous 5):211":0,"_uploadComplete:181":0,"abort:256":0,"isInProgress:268":0,"_upload:224":0,"upload:275":0,"end:280":0,"(anonymous 1):1":0};38_yuitest_coverage["build/io-upload-iframe/io-upload-iframe.js"].coveredLines = 80;39_yuitest_coverage["build/io-upload-iframe/io-upload-iframe.js"].coveredFunctions = 19;40_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 1);41YUI.add('io-upload-iframe', function (Y, NAME) {42/**43Extends the IO to enable file uploads, with HTML forms44using an iframe as the transport medium.45@module io46@submodule io-upload-iframe47@for IO48**/49_yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "(anonymous 1)", 1);50_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 11);51var w = Y.config.win,52 d = Y.config.doc,53 _std = (d.documentMode && d.documentMode >= 8),54 _d = decodeURIComponent,55 _end = Y.IO.prototype.end;56/**57 * Creates the iframe transported used in file upload58 * transactions, and binds the response event handler.59 *60 * @method _cFrame61 * @private62 * @param {Object} o Transaction object generated by _create().63 * @param {Object} c Configuration object passed to YUI.io().64 * @param {Object} io65 */66_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 27);67function _cFrame(o, c, io) {68 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_cFrame", 27);69_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 28);70var i = Y.Node.create('<iframe src="#" id="io_iframe' + o.id + '" name="io_iframe' + o.id + '" />');71 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 29);72i._node.style.position = 'absolute';73 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 30);74i._node.style.top = '-1000px';75 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 31);76i._node.style.left = '-1000px';77 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 32);78Y.one('body').appendChild(i);79 // Bind the onload handler to the iframe to detect the file upload response.80 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 34);81Y.on("load", function() { _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "(anonymous 2)", 34);82io._uploadComplete(o, c); }, '#io_iframe' + o.id);83}84/**85 * Removes the iframe transport used in the file upload86 * transaction.87 *88 * @method _dFrame89 * @private90 * @param {Number} id The transaction ID used in the iframe's creation.91 */92_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 45);93function _dFrame(id) {94 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_dFrame", 45);95_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 46);96Y.Event.purgeElement('#io_iframe' + id, false);97 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 47);98Y.one('body').removeChild(Y.one('#io_iframe' + id));99}100_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 50);101Y.mix(Y.IO.prototype, {102 /**103 * Parses the POST data object and creates hidden form elements104 * for each key-value, and appends them to the HTML form object.105 * @method appendData106 * @private107 * @static108 * @param {Object} f HTML form object.109 * @param {String} s The key-value POST data.110 * @return {Array} o Array of created fields.111 */112 _addData: function(f, s) {113 // Serialize an object into a key-value string using114 // querystring-stringify-simple.115 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_addData", 61);116_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 64);117if (Y.Lang.isObject(s)) {118 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 65);119s = Y.QueryString.stringify(s);120 }121 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 68);122var o = [],123 m = s.split('='),124 i, l;125 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 72);126for (i = 0, l = m.length - 1; i < l; i++) {127 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 73);128o[i] = d.createElement('input');129 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 74);130o[i].type = 'hidden';131 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 75);132o[i].name = _d(m[i].substring(m[i].lastIndexOf('&') + 1));133 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 76);134o[i].value = (i + 1 === l) ? _d(m[i + 1]) : _d(m[i + 1].substring(0, (m[i + 1].lastIndexOf('&'))));135 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 77);136f.appendChild(o[i]);137 }138 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 80);139return o;140 },141 /**142 * Removes the custom fields created to pass additional POST143 * data, along with the HTML form fields.144 * @method _removeData145 * @private146 * @static147 * @param {Object} f HTML form object.148 * @param {Object} o HTML form fields created from configuration.data.149 */150 _removeData: function(f, o) {151 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_removeData", 92);152_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 93);153var i, l;154 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 95);155for (i = 0, l = o.length; i < l; i++) {156 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 96);157f.removeChild(o[i]);158 }159 },160 /**161 * Sets the appropriate attributes and values to the HTML162 * form, in preparation of a file upload transaction.163 * @method _setAttrs164 * @private165 * @static166 * @param {Object} f HTML form object.167 * @param {Object} id The Transaction ID.168 * @param {Object} uri Qualified path to transaction resource.169 */170 _setAttrs: function(f, id, uri) {171 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_setAttrs", 110);172_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 111);173f.setAttribute('action', uri);174 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 112);175f.setAttribute('method', 'POST');176 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 113);177f.setAttribute('target', 'io_iframe' + id );178 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 114);179f.setAttribute(Y.UA.ie && !_std ? 'encoding' : 'enctype', 'multipart/form-data');180 },181 /**182 * Reset the HTML form attributes to their original values.183 * @method _resetAttrs184 * @private185 * @static186 * @param {Object} f HTML form object.187 * @param {Object} a Object of original attributes.188 */189 _resetAttrs: function(f, a) {190 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_resetAttrs", 125);191_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 126);192Y.Object.each(a, function(v, p) {193 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "(anonymous 3)", 126);194_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 127);195if (v) {196 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 128);197f.setAttribute(p, v);198 }199 else {200 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 131);201f.removeAttribute(p);202 }203 });204 },205 /**206 * Starts timeout count if the configuration object207 * has a defined timeout property.208 *209 * @method _startUploadTimeout210 * @private211 * @static212 * @param {Object} o Transaction object generated by _create().213 * @param {Object} c Configuration object passed to YUI.io().214 */215 _startUploadTimeout: function(o, c) {216 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_startUploadTimeout", 146);217_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 147);218var io = this;219 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 149);220io._timeout[o.id] = w.setTimeout(221 function() {222 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "(anonymous 4)", 150);223_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 151);224o.status = 0;225 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 152);226o.statusText = 'timeout';227 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 153);228io.complete(o, c);229 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 154);230io.end(o, c);231 }, c.timeout);232 },233 /**234 * Clears the timeout interval started by _startUploadTimeout().235 * @method _clearUploadTimeout236 * @private237 * @static238 * @param {Number} id - Transaction ID.239 */240 _clearUploadTimeout: function(id) {241 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_clearUploadTimeout", 165);242_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 166);243var io = this;244 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 168);245w.clearTimeout(io._timeout[id]);246 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 169);247delete io._timeout[id];248 },249 /**250 * Bound to the iframe's Load event and processes251 * the response data.252 * @method _uploadComplete253 * @private254 * @static255 * @param {Object} o The transaction object256 * @param {Object} c Configuration object for the transaction.257 */258 _uploadComplete: function(o, c) {259 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_uploadComplete", 181);260_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 182);261var io = this,262 d = Y.one('#io_iframe' + o.id).get('contentWindow.document'),263 b = d.one('body'),264 p;265 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 187);266if (c.timeout) {267 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 188);268io._clearUploadTimeout(o.id);269 }270 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 191);271try {272 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 192);273if (b) {274 // When a response Content-Type of "text/plain" is used, Firefox and Safari275 // will wrap the response string with <pre></pre>.276 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 195);277p = b.one('pre:first-child');278 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 196);279o.c.responseText = p ? p.get('text') : b.get('text');280 }281 else {282 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 199);283o.c.responseXML = d._node;284 }285 }286 catch (e) {287 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 203);288o.e = "upload failure";289 }290 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 206);291io.complete(o, c);292 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 207);293io.end(o, c);294 // The transaction is complete, so call _dFrame to remove295 // the event listener bound to the iframe transport, and then296 // destroy the iframe.297 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 211);298w.setTimeout( function() { _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "(anonymous 5)", 211);299_dFrame(o.id); }, 0);300 },301 /**302 * Uploads HTML form data, inclusive of files/attachments,303 * using the iframe created in _create to facilitate the transaction.304 * @method _upload305 * @private306 * @static307 * @param {Object} o The transaction object308 * @param {Object} uri Qualified path to transaction resource.309 * @param {Object} c Configuration object for the transaction.310 */311 _upload: function(o, uri, c) {312 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "_upload", 224);313_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 225);314var io = this,315 f = (typeof c.form.id === 'string') ? d.getElementById(c.form.id) : c.form.id,316 // Track original HTML form attribute values.317 attr = {318 action: f.getAttribute('action'),319 target: f.getAttribute('target')320 },321 fields;322 // Initialize the HTML form properties in case they are323 // not defined in the HTML form.324 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 236);325io._setAttrs(f, o.id, uri);326 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 237);327if (c.data) {328 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 238);329fields = io._addData(f, c.data);330 }331 // Start polling if a callback is present and the timeout332 // property has been defined.333 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 243);334if (c.timeout) {335 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 244);336io._startUploadTimeout(o, c);337 }338 // Start file upload.339 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 248);340f.submit();341 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 249);342io.start(o, c);343 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 250);344if (c.data) {345 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 251);346io._removeData(f, fields);347 }348 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 254);349return {350 id: o.id,351 abort: function() {352 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "abort", 256);353_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 257);354o.status = 0;355 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 258);356o.statusText = 'abort';357 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 259);358if (Y.one('#io_iframe' + o.id)) {359 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 260);360_dFrame(o.id);361 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 261);362io.complete(o, c);363 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 262);364io.end(o, c, attr);365 }366 else {367 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 265);368return false;369 }370 },371 isInProgress: function() {372 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "isInProgress", 268);373_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 269);374return Y.one('#io_iframe' + o.id) ? true : false;375 },376 io: io377 };378 },379 upload: function(o, uri, c) {380 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "upload", 275);381_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 276);382_cFrame(o, c, this);383 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 277);384return this._upload(o, uri, c);385 },386 end: function(transaction, config, attr) {387 _yuitest_coverfunc("build/io-upload-iframe/io-upload-iframe.js", "end", 280);388_yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 281);389if (config && config.form && config.form.upload) {390 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 282);391var io = this;392 // Restore HTML form attributes to their original values.393 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 284);394io._resetAttrs(f, attr);395 }396 _yuitest_coverline("build/io-upload-iframe/io-upload-iframe.js", 287);397return _end.call(this, transaction, config);398 }399});...

Full Screen

Full Screen

iframe.js

Source:iframe.js Github

copy

Full Screen

1/*2 * File: iframeResizer.js3 * Desc: Force iframes to size to content.4 * Requires: iframeResizer.contentWindow.js to be loaded into the target frame.5 * Author: David J. Bradshaw - dave@bradshaw.net6 * Contributor: Jure Mav - jure.mav@gmail.com7 * Contributor: Reed Dadoune - reed@dadoune.com8 */9;(function() {10 'use strict';11 var12 count = 0,13 firstRun = true,14 logEnabled = false,15 msgHeader = 'message',16 msgHeaderLen = msgHeader.length,17 msgId = '[iFrameSizer]', //Must match iframe msg ID18 msgIdLen = msgId.length,19 pagePosition = null,20 requestAnimationFrame = window.requestAnimationFrame,21 resetRequiredMethods = {max:1,scroll:1,bodyScroll:1,documentElementScroll:1},22 settings = {},23 timer = null,24 defaults = {25 autoResize : true,26 bodyBackground : null,27 bodyMargin : null,28 bodyMarginV1 : 8,29 bodyPadding : null,30 checkOrigin : true,31 enableInPageLinks : false,32 enablePublicMethods : false,33 heightCalculationMethod : 'offset',34 interval : 32,35 log : false,36 maxHeight : Infinity,37 maxWidth : Infinity,38 minHeight : 0,39 minWidth : 0,40 resizeFrom : 'parent',41 scrolling : false,42 sizeHeight : true,43 sizeWidth : false,44 tolerance : 0,45 closedCallback : function(){},46 initCallback : function(){},47 messageCallback : function(){},48 resizedCallback : function(){},49 scrollCallback : function(){return true;}50 };51 function addEventListener(obj,evt,func){52 if ('addEventListener' in window){53 obj.addEventListener(evt,func, false);54 } else if ('attachEvent' in window){//IE55 obj.attachEvent('on'+evt,func);56 }57 }58 function setupRequestAnimationFrame(){59 var60 vendors = ['moz', 'webkit', 'o', 'ms'],61 x;62 // Remove vendor prefixing if prefixed and break early if not63 for (x = 0; x < vendors.length && !requestAnimationFrame; x += 1) {64 requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];65 }66 if (!(requestAnimationFrame)){67 log(' RequestAnimationFrame not supported');68 }69 }70 function getMyID(){71 var retStr = 'Host page';72 if (window.top!==window.self){73 if (window.parentIFrame){74 retStr = window.parentIFrame.getId();75 } else {76 retStr = 'Nested host page';77 }78 }79 return retStr;80 }81 function formatLogMsg(msg){82 return msgId + '[' + getMyID() + ']' + msg;83 }84 function log(msg){85 if (logEnabled && ('object' === typeof window.console)){86 console.log(formatLogMsg(msg));87 }88 }89 function warn(msg){90 if ('object' === typeof window.console){91 console.warn(formatLogMsg(msg));92 }93 }94 function iFrameListener(event){95 function resizeIFrame(){96 function resize(){97 setSize(messageData);98 setPagePosition();99 settings[iframeID].resizedCallback(messageData);100 }101 ensureInRange('Height');102 ensureInRange('Width');103 syncResize(resize,messageData,'resetPage');104 }105 function closeIFrame(iframe){106 var iframeID = iframe.id;107 log(' Removing iFrame: '+iframeID);108 iframe.parentNode.removeChild(iframe);109 settings[iframeID].closedCallback(iframeID);110 delete settings[iframeID];111 log(' --');112 }113 function processMsg(){114 var data = msg.substr(msgIdLen).split(':');115 return {116 iframe: document.getElementById(data[0]),117 id: data[0],118 height: data[1],119 width: data[2],120 type: data[3]121 };122 }123 function ensureInRange(Dimension){124 var125 max = Number(settings[iframeID]['max'+Dimension]),126 min = Number(settings[iframeID]['min'+Dimension]),127 dimension = Dimension.toLowerCase(),128 size = Number(messageData[dimension]);129 if (min>max){130 throw new Error('Value for min'+Dimension+' can not be greater than max'+Dimension);131 }132 log(' Checking '+dimension+' is in range '+min+'-'+max);133 if (size<min) {134 size=min;135 log(' Set '+dimension+' to min value');136 }137 if (size>max) {138 size=max;139 log(' Set '+dimension+' to max value');140 }141 messageData[dimension]=''+size;142 }143 function isMessageFromIFrame(){144 function checkAllowedOrigin(){145 function checkList(){146 log(' Checking connection is from allowed list of origins: ' + checkOrigin);147 var i;148 for (i = 0; i < checkOrigin.length; i++) {149 if (checkOrigin[i] === origin) {150 return true;151 }152 }153 return false;154 }155 function checkSingle(){156 log(' Checking connection is from: '+remoteHost);157 return origin == remoteHost;158 }159 return checkOrigin.constructor === Array ? checkList() : checkSingle();160 }161 var162 origin = event.origin,163 checkOrigin = settings[iframeID].checkOrigin,164 remoteHost = messageData.iframe.src.split('/').slice(0,3).join('/');165 if (checkOrigin) {166 if ((''+origin !== 'null') && !checkAllowedOrigin()) {167 throw new Error(168 'Unexpected message received from: ' + origin +169 ' for ' + messageData.iframe.id +170 '. Message was: ' + event.data +171 '. This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.'172 );173 }174 }175 return true;176 }177 function isMessageForUs(){178 return msgId === ('' + msg).substr(0,msgIdLen); //''+Protects against non-string msg179 }180 function isMessageFromMetaParent(){181 //test if this message is from a parent above us. This is an ugly test, however, updating182 //the message format would break backwards compatibility.183 var retCode = messageData.type in {'true':1,'false':1,'undefined':1};184 if (retCode){185 log(' Ignoring init message from meta parent page');186 }187 return retCode;188 }189 function getMsgBody(offset){190 return msg.substr(msg.indexOf(':')+msgHeaderLen+offset);191 }192 function forwardMsgFromIFrame(msgBody){193 log(' MessageCallback passed: {iframe: '+ messageData.iframe.id + ', message: ' + msgBody + '}');194 settings[iframeID].messageCallback({195 iframe: messageData.iframe,196 message: JSON.parse(msgBody)197 });198 log(' --');199 }200 function checkIFrameExists(){201 if (null === messageData.iframe) {202 warn(' IFrame ('+messageData.id+') not found');203 return false;204 }205 return true;206 }207 function getElementPosition(target){208 var209 iFramePosition = target.getBoundingClientRect();210 getPagePosition();211 return {212 x: parseInt(iFramePosition.left, 10) + parseInt(pagePosition.x, 10),213 y: parseInt(iFramePosition.top, 10) + parseInt(pagePosition.y, 10)214 };215 }216 function scrollRequestFromChild(addOffset){217 function reposition(){218 pagePosition = newPosition;219 scrollTo();220 log(' --');221 }222 function calcOffset(){223 return {224 x: Number(messageData.width) + offset.x,225 y: Number(messageData.height) + offset.y226 };227 }228 var229 offset = addOffset ? getElementPosition(messageData.iframe) : {x:0,y:0},230 newPosition = calcOffset();231 log(' Reposition requested from iFrame (offset x:'+offset.x+' y:'+offset.y+')');232 if(window.top!==window.self){233 if (window.parentIFrame){234 if (addOffset){235 parentIFrame.scrollToOffset(newPosition.x,newPosition.y);236 } else {237 parentIFrame.scrollTo(messageData.width,messageData.height);238 }239 } else {240 warn(' Unable to scroll to requested position, window.parentIFrame not found');241 }242 } else {243 reposition();244 }245 }246 function scrollTo(){247 if (false !== settings[iframeID].scrollCallback(pagePosition)){248 setPagePosition();249 }250 }251 function findTarget(location){252 var hash = location.split("#")[1] || "";253 var hashData = decodeURIComponent(hash);254 function jumpToTarget(target){255 var jumpPosition = getElementPosition(target);256 log(' Moving to in page link (#'+hash+') at x: '+jumpPosition.x+' y: '+jumpPosition.y);257 pagePosition = {258 x: jumpPosition.x,259 y: jumpPosition.y260 };261 scrollTo();262 log(' --');263 }264 var target = document.getElementById(hashData) || document.getElementsByName(hashData)[0];265 if(window.top!==window.self){266 if (window.parentIFrame){267 parentIFrame.moveToAnchor(hash);268 } else {269 log(' In page link #'+hash+' not found and window.parentIFrame not found');270 }271 } else if (target){272 jumpToTarget(target);273 } else {274 log(' In page link #'+hash+' not found');275 }276 }277 function actionMsg(){278 switch(messageData.type){279 case 'close':280 closeIFrame(messageData.iframe);281 break;282 case 'message':283 forwardMsgFromIFrame(getMsgBody(6));284 break;285 case 'scrollTo':286 scrollRequestFromChild(false);287 break;288 case 'scrollToOffset':289 scrollRequestFromChild(true);290 break;291 case 'inPageLink':292 findTarget(getMsgBody(9));293 break;294 case 'reset':295 resetIFrame(messageData);296 break;297 case 'init':298 resizeIFrame();299 settings[iframeID].initCallback(messageData.iframe);300 break;301 default:302 resizeIFrame();303 }304 }305 function hasSettings(iframeID){306 var retBool = true;307 if (!settings[iframeID]){308 retBool = false;309 warn(messageData.type + ' No settings for ' + iframeID + '. Message was: ' + msg);310 }311 return retBool;312 }313 var314 msg = event.data,315 messageData = {},316 iframeID = null;317 if (isMessageForUs()){318 messageData = processMsg();319 iframeID = messageData.id;320 if (!isMessageFromMetaParent() && hasSettings(iframeID)){321 logEnabled = settings[iframeID].log;322 log(' Received: '+msg);323 if ( checkIFrameExists() && isMessageFromIFrame() ){324 actionMsg();325 firstRun = false;326 }327 }328 }329 }330 function getPagePosition (){331 if(null === pagePosition){332 pagePosition = {333 x: (window.pageXOffset !== undefined) ? window.pageXOffset : document.documentElement.scrollLeft,334 y: (window.pageYOffset !== undefined) ? window.pageYOffset : document.documentElement.scrollTop335 };336 log(' Get page position: '+pagePosition.x+','+pagePosition.y);337 }338 }339 function setPagePosition(){340 if(null !== pagePosition){341 window.scrollTo(pagePosition.x,pagePosition.y);342 log(' Set page position: '+pagePosition.x+','+pagePosition.y);343 pagePosition = null;344 }345 }346 function resetIFrame(messageData){347 function reset(){348 setSize(messageData);349 trigger('reset','reset',messageData.iframe,messageData.id);350 }351 log(' Size reset requested by '+('init'===messageData.type?'host page':'iFrame'));352 getPagePosition();353 syncResize(reset,messageData,'init');354 }355 function setSize(messageData){356 function setDimension(dimension){357 messageData.iframe.style[dimension] = messageData[dimension] + 'px';358 log(359 ' IFrame (' + iframeID +360 ') ' + dimension +361 ' set to ' + messageData[dimension] + 'px'362 );363 }364 var iframeID = messageData.iframe.id;365 if( settings[iframeID].sizeHeight) { setDimension('height'); }366 if( settings[iframeID].sizeWidth ) { setDimension('width'); }367 }368 function syncResize(func,messageData,doNotSync){369 if(doNotSync!==messageData.type && requestAnimationFrame){370 log(' Requesting animation frame');371 requestAnimationFrame(func);372 } else {373 func();374 }375 }376 function trigger(calleeMsg,msg,iframe,id){377 if(iframe && iframe.contentWindow){378 log('[' + calleeMsg + '] Sending msg to iframe ('+msg+')');379 iframe.contentWindow.postMessage( msgId + msg, '*' );380 } else {381 warn('[' + calleeMsg + '] IFrame not found');382 if(settings[id]) delete settings[id];383 }384 }385 function setupIFrame(options){386 function setLimits(){387 function addStyle(style){388 if ((Infinity !== settings[iframeID][style]) && (0 !== settings[iframeID][style])){389 iframe.style[style] = settings[iframeID][style] + 'px';390 log(' Set '+style+' = '+settings[iframeID][style]+'px');391 }392 }393 addStyle('maxHeight');394 addStyle('minHeight');395 addStyle('maxWidth');396 addStyle('minWidth');397 }398 function ensureHasId(iframeID){399 if (''===iframeID){400 iframe.id = iframeID = 'iFrameResizer' + count++;401 logEnabled = (options || {}).log;402 log(' Added missing iframe ID: '+ iframeID +' (' + iframe.src + ')');403 }404 return iframeID;405 }406 function setScrolling(){407 log(' IFrame scrolling ' + (settings[iframeID].scrolling ? 'enabled' : 'disabled') + ' for ' + iframeID);408 iframe.style.overflow = false === settings[iframeID].scrolling ? 'hidden' : 'auto';409 iframe.scrolling = false === settings[iframeID].scrolling ? 'no' : 'yes';410 }411 //The V1 iFrame script expects an int, where as in V2 expects a CSS412 //string value such as '1px 3em', so if we have an int for V2, set V1=V2413 //and then convert V2 to a string PX value.414 function setupBodyMarginValues(){415 if (('number'===typeof(settings[iframeID].bodyMargin)) || ('0'===settings[iframeID].bodyMargin)){416 settings[iframeID].bodyMarginV1 = settings[iframeID].bodyMargin;417 settings[iframeID].bodyMargin = '' + settings[iframeID].bodyMargin + 'px';418 }419 }420 function createOutgoingMsg(){421 return iframeID +422 ':' + settings[iframeID].bodyMarginV1 +423 ':' + settings[iframeID].sizeWidth +424 ':' + settings[iframeID].log +425 ':' + settings[iframeID].interval +426 ':' + settings[iframeID].enablePublicMethods +427 ':' + settings[iframeID].autoResize +428 ':' + settings[iframeID].bodyMargin +429 ':' + settings[iframeID].heightCalculationMethod +430 ':' + settings[iframeID].bodyBackground +431 ':' + settings[iframeID].bodyPadding +432 ':' + settings[iframeID].tolerance +433 ':' + settings[iframeID].enableInPageLinks +434 ':' + settings[iframeID].resizeFrom;435 }436 function init(msg){437 //We have to call trigger twice, as we can not be sure if all438 //iframes have completed loading when this code runs. The439 //event listener also catches the page changing in the iFrame.440 addEventListener(iframe,'load',function(){441 var fr = firstRun; // Reduce scope of var to function, because IE8's JS execution442 // context stack is borked and this value gets externally443 // changed midway through running this function.444 trigger('iFrame.onload',msg,iframe);445 if (!fr && settings[iframeID].heightCalculationMethod in resetRequiredMethods){446 resetIFrame({447 iframe:iframe,448 height:0,449 width:0,450 type:'init'451 });452 }453 });454 trigger('init',msg,iframe);455 }456 function checkOptions(options){457 if ('object' !== typeof options){458 throw new TypeError('Options is not an object.');459 }460 }461 function processOptions(options){462 options = options || {};463 settings[iframeID] = {};464 checkOptions(options);465 for (var option in defaults) {466 if (defaults.hasOwnProperty(option)){467 settings[iframeID][option] = options.hasOwnProperty(option) ? options[option] : defaults[option];468 }469 }470 logEnabled = settings[iframeID].log;471 }472 var473 /*jshint validthis:true */474 iframe = this,475 iframeID = ensureHasId(iframe.id);476 processOptions(options);477 setScrolling();478 setLimits();479 setupBodyMarginValues();480 init(createOutgoingMsg());481 }482 function throttle(fn,time){483 if (null === timer){484 timer = setTimeout(function(){485 timer = null;486 fn();487 }, time);488 }489 }490 function winResize(){491 throttle(function(){492 for (var iframeId in settings){493 if('parent' === settings[iframeId].resizeFrom){494 trigger('Window resize','resize',document.getElementById(iframeId),iframeId);495 }496 }497 },66);498 }499 function factory(){500 setupRequestAnimationFrame();501 addEventListener(window,'message',iFrameListener);502 addEventListener(window,'resize', winResize);503 function init(element, options){504 if(!element.tagName) {505 throw new TypeError('Object is not a valid DOM element');506 } else if ('IFRAME' !== element.tagName.toUpperCase()) {507 throw new TypeError('Expected <IFRAME> tag, found <'+element.tagName+'>.');508 } else {509 setupIFrame.call(element, options);510 }511 }512 return function iFrameResizeF(options,target){513 switch (typeof(target)){514 case 'undefined':515 case 'string':516 Array.prototype.forEach.call( document.querySelectorAll( target || 'iframe' ), function (element) {517 init(element, options);518 });519 break;520 case 'object':521 init(target, options);522 break;523 default:524 throw new TypeError('Unexpected data type ('+typeof(target)+').');525 }526 };527 }528 function createJQueryPublicMethod($){529 $.fn.iFrameResize = function $iFrameResizeF(options) {530 return this.filter('iframe').each(function (index, element) {531 setupIFrame.call(element, options);532 }).end();533 };534 }535 if (window.jQuery) { createJQueryPublicMethod(jQuery); }536 if (typeof define === 'function' && define.amd) {537 define([],factory);538 } else if (typeof module === 'object' && typeof module.exports === 'object') { //Node for browserfy539 module.exports = factory();540 } else {541 window.iFrameResize = window.iFrameResize || factory();542 }...

Full Screen

Full Screen

aui-resize-iframe-debug.js

Source:aui-resize-iframe-debug.js Github

copy

Full Screen

1AUI.add('aui-resize-iframe', function(A) {2var Lang = A.Lang,3 isString = Lang.isString,4 RESIZE_IFRAME = 'resizeiframe',5 getClassName = A.getClassName,6 HEIGHT = 'height',7 HIDDEN = 'hidden',8 NO = 'no',9 SCROLLING = 'scrolling',10 WIDTH = 'width',11 CSS_RESIZE_IFRAME_MONITORED_HEIGHT = getClassName(RESIZE_IFRAME, 'monitored', HEIGHT);12ResizeIframe = A.Component.create(13 {14 NAME: RESIZE_IFRAME,15 NS: RESIZE_IFRAME,16 EXTENDS: A.Plugin.Base,17 ATTRS: {18 height: {19 value: 020 },21 monitorHeight: {22 value: true23 },24 width: {25 value: null26 }27 },28 prototype: {29 initializer: function(config) {30 var instance = this;31 var frame = instance.get('host');32 instance.node = frame;33 instance._iframeEl = frame.getDOM();34 instance._defaultHeight = config.height;35 instance.bindUI();36 instance.syncUI();37 },38 bindUI: function() {39 var instance = this;40 instance.after('heightChange', instance._afterHeightChange);41 instance.after('monitorHeightChange', instance._afterMonitorHeightChange);42 instance.after('widthChange', instance._afterWidthChange);43 },44 syncUI: function() {45 var instance = this;46 instance._uiSetMonitorHeight(instance.get('monitorHeight'));47 },48 destructor: function() {49 var instance = this;50 instance._uiSetMonitorHeight(false);51 },52 pauseMonitor: function() {53 var instance = this;54 instance._clearInterval();55 },56 restartMonitor: function() {57 var instance = this;58 if (instance.get('monitorHeight')) {59 instance._setInterval();60 }61 },62 _afterHeightChange: function(event) {63 var instance = this;64 instance.set('monitorHeight', false);65 instance._uiSetHeight(event.newVal);66 },67 _afterMonitorHeightChange: function(event) {68 var instance = this;69 instance._uiSetMonitorHeight(event.newVal);70 },71 _afterWidthChange: function(event) {72 var instance = this;73 instance._uiSetWidth(event.newVal);74 },75 _clearInterval: function() {76 var instance = this;77 var iframeDoc = instance._iframeDoc;78 if (iframeDoc) {79 var docEl = iframeDoc.documentElement;80 if (docEl) {81 docEl.style.overflowY = '';82 }83 }84 if (instance._intervalId) {85 A.clearInterval(instance._intervalId);86 instance._intervalId = null;87 }88 },89 _onResize: function() {90 var instance = this;91 instance._iframeDoc = null;92 var newHeight = instance._iframeHeight;93 var iframeDoc;94 var iframeWin;95 try {96 iframeWin = instance._iframeEl.contentWindow;97 iframeDoc = iframeWin.document;98 instance._iframeDoc = iframeDoc;99 }100 catch (e) {101 }102 if (iframeDoc && iframeWin) {103 newHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc, instance._iframeHeight);104 instance._uiSetHeight(newHeight);105 }106 else if (!iframeDoc) {107 instance._clearInterval();108 instance._uiSetHeight(instance._defaultHeight);109 }110 },111 _setInterval: function(event) {112 var instance = this;113 if (!instance._intervalId) {114 instance._onResize();115 instance._intervalId = A.setInterval(instance._onResize, 100, instance);116 }117 },118 _uiSetHeight: function(value) {119 var instance = this;120 if (instance._iframeHeight != value) {121 instance._iframeHeight = value;122 instance.node.setStyle(HEIGHT, value);123 }124 },125 _uiSetMonitorHeight: function(monitorHeight) {126 var instance = this;127 var iframe = instance.node;128 if (monitorHeight) {129 instance._setInterval();130 instance._loadHandle = iframe.on('load', instance._setInterval, instance);131 iframe.addClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);132 }133 else {134 instance._clearInterval();135 if (instance._loadHandle) {136 instance._loadHandle.detach();137 }138 iframe.removeClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);139 }140 },141 _uiSetWidth: function(value) {142 var instance = this;143 instance.node.setStyle(WIDTH, value);144 },145 _iframeHeight: 0146 }147 }148);149A.mix(150 ResizeIframe,151 {152 getContentHeight: function(iframeWin) {153 var contentHeight = null;154 try {155 var iframeDoc;156 if (iframeWin.nodeName && iframeWin.nodeName.toLowerCase() == 'iframe') {157 iframeWin = iframeWin.contentWindow;158 }159 else if (A.instanceOf(iframeWin, A.Node)) {160 iframeWin = iframeWin.getDOM().contentWindow;161 }162 iframeDoc = iframeWin.document;163 contentHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc);164 }165 catch (e) {166 }167 return contentHeight;168 },169 _getContentHeight: function(iframeWin, iframeDoc, fallbackHeight) {170 var contentHeight = null;171 if (iframeDoc && iframeWin.location.href != 'about:blank') {172 var docEl = iframeDoc.documentElement;173 var iframeBody = iframeDoc.body;174 if (docEl) {175 docEl.style.overflowY = HIDDEN;176 }177 var docOffsetHeight = (iframeBody && iframeBody.offsetHeight) || 0;178 var standardsMode = (iframeDoc.compatMode == 'CSS1Compat');179 if (standardsMode && docOffsetHeight) {180 contentHeight = docOffsetHeight;181 }182 else {183 contentHeight = ResizeIframe._getQuirksHeight(iframeWin) || fallbackHeight;184 }185 }186 return contentHeight;187 },188 _getQuirksHeight: function(iframeWin) {189 var contentHeight = 0;190 var iframeDoc = iframeWin.document;191 var docEl = iframeDoc && iframeDoc.documentElement;192 var iframeBody = iframeDoc && iframeDoc.body;193 var viewPortHeight = 0;194 if (iframeWin.innerHeight) {195 viewPortHeight = iframeWin.innerHeight;196 }197 else if (docEl && docEl.clientHeight) {198 viewPortHeight = docEl.clientHeight;199 }200 else if (iframeBody) {201 viewPortHeight = iframeBody.clientHeight;202 }203 if (iframeDoc) {204 var docClientHeight;205 var docScrollHeight;206 var docOffsetHeight = (iframeBody && iframeBody.offsetHeight);207 if (docEl) {208 docClientHeight = docEl.clientHeight;209 docScrollHeight = docEl.scrollHeight;210 docOffsetHeight = docEl.offsetHeight;211 }212 if (docClientHeight != docOffsetHeight && iframeBody) {213 docOffsetHeight = iframeBody.offsetHeight;214 docScrollHeight = iframeBody.scrollHeight;215 }216 var compareNum;217 if (docScrollHeight > viewPortHeight) {218 compareNum = Math.max;219 }220 else {221 compareNum = Math.min;222 }223 contentHeight = compareNum(docScrollHeight, docOffsetHeight);224 }225 return contentHeight;226 }227 }228);229A.Plugin.ResizeIframe = ResizeIframe;...

Full Screen

Full Screen

aui-resize-iframe.js

Source:aui-resize-iframe.js Github

copy

Full Screen

1AUI.add('aui-resize-iframe', function(A) {2var Lang = A.Lang,3 isString = Lang.isString,4 RESIZE_IFRAME = 'resizeiframe',5 getClassName = A.getClassName,6 HEIGHT = 'height',7 HIDDEN = 'hidden',8 NO = 'no',9 SCROLLING = 'scrolling',10 WIDTH = 'width',11 CSS_RESIZE_IFRAME_MONITORED_HEIGHT = getClassName(RESIZE_IFRAME, 'monitored', HEIGHT);12ResizeIframe = A.Component.create(13 {14 NAME: RESIZE_IFRAME,15 NS: RESIZE_IFRAME,16 EXTENDS: A.Plugin.Base,17 ATTRS: {18 height: {19 value: 020 },21 monitorHeight: {22 value: true23 },24 width: {25 value: null26 }27 },28 prototype: {29 initializer: function(config) {30 var instance = this;31 var frame = instance.get('host');32 instance.node = frame;33 instance._iframeEl = frame.getDOM();34 instance._defaultHeight = config.height;35 instance.bindUI();36 instance.syncUI();37 },38 bindUI: function() {39 var instance = this;40 instance.after('heightChange', instance._afterHeightChange);41 instance.after('monitorHeightChange', instance._afterMonitorHeightChange);42 instance.after('widthChange', instance._afterWidthChange);43 },44 syncUI: function() {45 var instance = this;46 instance._uiSetMonitorHeight(instance.get('monitorHeight'));47 },48 destructor: function() {49 var instance = this;50 instance._uiSetMonitorHeight(false);51 },52 pauseMonitor: function() {53 var instance = this;54 instance._clearInterval();55 },56 restartMonitor: function() {57 var instance = this;58 if (instance.get('monitorHeight')) {59 instance._setInterval();60 }61 },62 _afterHeightChange: function(event) {63 var instance = this;64 instance.set('monitorHeight', false);65 instance._uiSetHeight(event.newVal);66 },67 _afterMonitorHeightChange: function(event) {68 var instance = this;69 instance._uiSetMonitorHeight(event.newVal);70 },71 _afterWidthChange: function(event) {72 var instance = this;73 instance._uiSetWidth(event.newVal);74 },75 _clearInterval: function() {76 var instance = this;77 var iframeDoc = instance._iframeDoc;78 if (iframeDoc) {79 var docEl = iframeDoc.documentElement;80 if (docEl) {81 docEl.style.overflowY = '';82 }83 }84 if (instance._intervalId) {85 A.clearInterval(instance._intervalId);86 instance._intervalId = null;87 }88 },89 _onResize: function() {90 var instance = this;91 instance._iframeDoc = null;92 var newHeight = instance._iframeHeight;93 var iframeDoc;94 var iframeWin;95 try {96 iframeWin = instance._iframeEl.contentWindow;97 iframeDoc = iframeWin.document;98 instance._iframeDoc = iframeDoc;99 }100 catch (e) {101 }102 if (iframeDoc && iframeWin) {103 newHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc, instance._iframeHeight);104 instance._uiSetHeight(newHeight);105 }106 else if (!iframeDoc) {107 instance._clearInterval();108 instance._uiSetHeight(instance._defaultHeight);109 }110 },111 _setInterval: function(event) {112 var instance = this;113 if (!instance._intervalId) {114 instance._onResize();115 instance._intervalId = A.setInterval(instance._onResize, 100, instance);116 }117 },118 _uiSetHeight: function(value) {119 var instance = this;120 if (instance._iframeHeight != value) {121 instance._iframeHeight = value;122 instance.node.setStyle(HEIGHT, value);123 }124 },125 _uiSetMonitorHeight: function(monitorHeight) {126 var instance = this;127 var iframe = instance.node;128 if (monitorHeight) {129 instance._setInterval();130 instance._loadHandle = iframe.on('load', instance._setInterval, instance);131 iframe.addClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);132 }133 else {134 instance._clearInterval();135 if (instance._loadHandle) {136 instance._loadHandle.detach();137 }138 iframe.removeClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);139 }140 },141 _uiSetWidth: function(value) {142 var instance = this;143 instance.node.setStyle(WIDTH, value);144 },145 _iframeHeight: 0146 }147 }148);149A.mix(150 ResizeIframe,151 {152 getContentHeight: function(iframeWin) {153 var contentHeight = null;154 try {155 var iframeDoc;156 if (iframeWin.nodeName && iframeWin.nodeName.toLowerCase() == 'iframe') {157 iframeWin = iframeWin.contentWindow;158 }159 else if (A.instanceOf(iframeWin, A.Node)) {160 iframeWin = iframeWin.getDOM().contentWindow;161 }162 iframeDoc = iframeWin.document;163 contentHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc);164 }165 catch (e) {166 }167 return contentHeight;168 },169 _getContentHeight: function(iframeWin, iframeDoc, fallbackHeight) {170 var contentHeight = null;171 if (iframeDoc && iframeWin.location.href != 'about:blank') {172 var docEl = iframeDoc.documentElement;173 var iframeBody = iframeDoc.body;174 if (docEl) {175 docEl.style.overflowY = HIDDEN;176 }177 var docOffsetHeight = (iframeBody && iframeBody.offsetHeight) || 0;178 var standardsMode = (iframeDoc.compatMode == 'CSS1Compat');179 if (standardsMode && docOffsetHeight) {180 contentHeight = docOffsetHeight;181 }182 else {183 contentHeight = ResizeIframe._getQuirksHeight(iframeWin) || fallbackHeight;184 }185 }186 return contentHeight;187 },188 _getQuirksHeight: function(iframeWin) {189 var contentHeight = 0;190 var iframeDoc = iframeWin.document;191 var docEl = iframeDoc && iframeDoc.documentElement;192 var iframeBody = iframeDoc && iframeDoc.body;193 var viewPortHeight = 0;194 if (iframeWin.innerHeight) {195 viewPortHeight = iframeWin.innerHeight;196 }197 else if (docEl && docEl.clientHeight) {198 viewPortHeight = docEl.clientHeight;199 }200 else if (iframeBody) {201 viewPortHeight = iframeBody.clientHeight;202 }203 if (iframeDoc) {204 var docClientHeight;205 var docScrollHeight;206 var docOffsetHeight = (iframeBody && iframeBody.offsetHeight);207 if (docEl) {208 docClientHeight = docEl.clientHeight;209 docScrollHeight = docEl.scrollHeight;210 docOffsetHeight = docEl.offsetHeight;211 }212 if (docClientHeight != docOffsetHeight && iframeBody) {213 docOffsetHeight = iframeBody.offsetHeight;214 docScrollHeight = iframeBody.scrollHeight;215 }216 var compareNum;217 if (docScrollHeight > viewPortHeight) {218 compareNum = Math.max;219 }220 else {221 compareNum = Math.min;222 }223 contentHeight = compareNum(docScrollHeight, docOffsetHeight);224 }225 return contentHeight;226 }227 }228);229A.Plugin.ResizeIframe = ResizeIframe;...

Full Screen

Full Screen

iframemask_test.js

Source:iframemask_test.js Github

copy

Full Screen

1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14goog.provide('goog.ui.IframeMaskTest');15goog.setTestOnly('goog.ui.IframeMaskTest');16goog.require('goog.dom');17goog.require('goog.dom.TagName');18goog.require('goog.dom.iframe');19goog.require('goog.structs.Pool');20goog.require('goog.style');21goog.require('goog.testing.MockClock');22goog.require('goog.testing.StrictMock');23goog.require('goog.testing.jsunit');24goog.require('goog.ui.IframeMask');25goog.require('goog.ui.Popup');26goog.require('goog.ui.PopupBase');27goog.require('goog.userAgent');28var iframeMask;29var mockClock;30function setUp() {31 goog.dom.getElement('sandbox').innerHTML = '<div id="popup"></div>';32 mockClock = new goog.testing.MockClock(true);33 iframeMask = new goog.ui.IframeMask();34}35function tearDown() {36 iframeMask.dispose();37 mockClock.dispose();38 assertNoIframes();39}40function findOneAndOnlyIframe() {41 var iframes = document.getElementsByTagName(goog.dom.TagName.IFRAME);42 assertEquals('There should be exactly 1 iframe in the document',43 1, iframes.length);44 return iframes[0];45}46function assertNoIframes() {47 assertEquals('Expected no iframes in the document', 0,48 goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.IFRAME).length);49}50function testApplyFullScreenMask() {51 iframeMask.applyMask();52 var iframe = findOneAndOnlyIframe();53 assertEquals('block', iframe.style.display);54 assertEquals('absolute', iframe.style.position);55 // coerce zindex to a string56 assertEquals('1', iframe.style.zIndex + '');57 iframeMask.hideMask();58 assertEquals('none', iframe.style.display);59}60function testApplyOpacity() {61 iframeMask.setOpacity(0.3);62 iframeMask.applyMask();63 if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {64 assertContains('Expected opactity to be set in the CSS style',65 '30', findOneAndOnlyIframe().style.cssText);66 } else {67 assertContains('Expected opactity to be set in the CSS style',68 '0.3', findOneAndOnlyIframe().style.cssText);69 }70}71function testApplyZIndex() {72 iframeMask.setZIndex(5);73 iframeMask.applyMask();74 // coerce zindex to a string75 assertEquals('5', findOneAndOnlyIframe().style.zIndex + '');76}77function testSnapElement() {78 iframeMask.setSnapElement(goog.dom.getElement('popup'));79 iframeMask.applyMask();80 var iframe = findOneAndOnlyIframe();81 var bounds = goog.style.getBounds(iframe);82 assertEquals(100, bounds.left);83 assertEquals(900, bounds.top);84 assertEquals(300, bounds.width);85 assertEquals(400, bounds.height);86 iframeMask.setSnapElement(document.documentElement);87 // Make sure that snapping to a different element changes the bounds.88 assertNotEquals('Snap element not updated',89 400, goog.style.getBounds(iframe).height);90}91function testAttachToPopup() {92 var popup = new goog.ui.Popup(goog.dom.getElement('popup'));93 iframeMask.listenOnTarget(popup, goog.ui.PopupBase.EventType.SHOW,94 goog.ui.PopupBase.EventType.HIDE, goog.dom.getElement('popup'));95 assertNoIframes();96 popup.setVisible(true);97 assertNoIframes();98 // Tick because the showing of the iframe mask happens asynchronously.99 // (Otherwise the handling of the mousedown can take so long that a bounce100 // occurs).101 mockClock.tick(1);102 var iframe = findOneAndOnlyIframe();103 var bounds = goog.style.getBounds(iframe);104 assertEquals(300, bounds.width);105 assertEquals(400, bounds.height);106 assertEquals('block', iframe.style.display);107 popup.setVisible(false);108 assertEquals('none', iframe.style.display);109}110function testQuickHidingPopup() {111 var popup = new goog.ui.Popup(goog.dom.getElement('popup'));112 iframeMask.listenOnTarget(popup, goog.ui.PopupBase.EventType.SHOW,113 goog.ui.PopupBase.EventType.HIDE);114 assertNoIframes();115 popup.setVisible(true);116 assertNoIframes();117 popup.setVisible(false);118 assertNoIframes();119 // Tick because the showing of the iframe mask happens asynchronously.120 // (Otherwise the handling of the mousedown can take so long that a bounce121 // occurs).122 mockClock.tick(1);123 assertNoIframes();124}125function testRemoveHandlers() {126 var popup = new goog.ui.Popup(goog.dom.getElement('popup'));127 iframeMask.listenOnTarget(popup, goog.ui.PopupBase.EventType.SHOW,128 goog.ui.PopupBase.EventType.HIDE);129 iframeMask.removeHandlers();130 popup.setVisible(true);131 // Tick because the showing of the iframe mask happens asynchronously.132 // (Otherwise the handling of the mousedown can take so long that a bounce133 // occurs).134 mockClock.tick(1);135 assertNoIframes();136}137function testIframePool() {138 var iframe = goog.dom.iframe.createBlank(goog.dom.getDomHelper());139 var mockPool = new goog.testing.StrictMock(goog.structs.Pool);140 mockPool.getObject();141 mockPool.$returns(iframe);142 mockPool.$replay();143 iframeMask.dispose();144 // Create a new iframe mask with a pool, and verify that it checks145 // its iframe out of the pool instead of creating one.146 iframeMask = new goog.ui.IframeMask(null, mockPool);147 iframeMask.applyMask();148 mockPool.$verify();149 findOneAndOnlyIframe();150 mockPool.$reset();151 mockPool.releaseObject(iframe);152 mockPool.$replay();153 // When the iframe mask has a pool, the pool is responsible for154 // removing the iframe from the DOM.155 iframeMask.hideMask();156 mockPool.$verify();157 findOneAndOnlyIframe();158 // And showing the iframe again should check it out of the pool again.159 mockPool.$reset();160 mockPool.getObject();161 mockPool.$returns(iframe);162 mockPool.$replay();163 iframeMask.applyMask();164 mockPool.$verify();165 // When the test is over, the iframe mask should be disposed. Make sure166 // that the pool removes the iframe from the page.167 mockPool.$reset();168 mockPool.releaseObject(iframe);169 mockPool.$does(function() {170 goog.dom.removeNode(iframe);171 });172 mockPool.$replay();...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var chromy = new Chromy({ port: 9222, visible: true });2chromy.chain()3 .wait('#hplogo')4 .screenshot()5 .result(function (screenshot) {6 fs.writeFileSync('screenshot.png', screenshot);7 })8 .end()9 .then(function () {10 chromy.close();11 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer')2const browser = puppeteer.launch({ headless: false, args: ['--no-sandbox'] })3const page = browser.newPage()4page.goto(url)5page.evaluate(() => {6})7.then(title => {8 console.log(title)9})10.then(() => {11 browser.close()12})

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromy = require('chromy');2chromy.chain()3 .goto(url)4 .evaluate(() => {5 return document.title;6 })7 .result((title) => {8 console.log(title);9 })10 .end()11 .then(() => {12 console.log('success');13 })14 .catch((e) => {15 console.log(e);16 });17### chromy.chain()18### chain.goto(url)19### chain.evaluate(fn)20### chain.result(fn)21### chain.end()22### chain.then(fn)23### chain.catch(fn)24### chain.finally(fn)25### chain.waitFor(fn)26### chain.waitForNavigation()27### chain.waitForAnimation()28### chain.waitForSelector(selector)29### chain.click(selector)30### chain.type(selector, text)31### chain.upload(selector, filePath)32### chain.screenshot(filePath)33### chain.scrollToBottom()34### chain.scrollToTop()35### chain.scrollIntoView(selector)36### chain.scrollBy(x, y)37### chain.scrollBySelector(selector, x, y)38### chain.goBack()39### chain.goForward()40### chain.reload()41### chain.resize(width, height)42### chain.emulate(type)43### chain.emulateMedia(media)

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromy = require('chromy');2const fs = require('fs');3const path = require('path');4(async () => {5 const chromy = new Chromy({visible: true, waitTimeout: 5000});6 await chromy.wait(1000);7 await chromy.screenshot({path: 'google.png'});8 await chromy.close();9})();10const chromy = require('chromy');11const fs = require('fs');12const path = require('path');13(async () => {14 const chromy = new Chromy({visible: true, waitTimeout: 5000});15 await chromy.wait(1000);16 await chromy.screenshot({path: 'google.png'});17 await chromy.close();18})();19const chromy = require('chromy');20const fs = require('fs');21const path = require('path');22(async () => {23 const chromy = new Chromy({visible: true, waitTimeout: 5000});

Full Screen

Using AI Code Generation

copy

Full Screen

1var chromy = new Chromy({ port: 9222, visible: true, waitTimeout: 5000, frame: true });2chromy.chain()3 .evaluate(function() {4 return document.querySelector('title').innerText;5 })6 .result(function(title) {7 console.log(title);8 })9 .end()10 .then(function() {11 console.log('Done');12 })13 .catch(function(err) {14 console.log('Error:', err);15 });16var chromy = new Chromy({ port: 9222, visible: true, waitTimeout: 5000, frame: true });17chromy.chain()18 .evaluate(function() {19 return document.querySelector('title').innerText;20 })21 .result(function(title) {22 console.log(title);23 })24 .end()25 .then(function() {26 console.log('Done');27 })28 .catch(function(err) {29 console.log('Error:', err);30 });31var chromy = new Chromy({ port: 9222, visible: true, waitTimeout: 5000, frame: true });32chromy.chain()33 .evaluate(function() {34 return document.querySelector('title').innerText;35 })36 .result(function(title) {37 console.log(title);38 })39 .end()40 .then(function() {41 console.log('Done');42 })43 .catch(function(err) {44 console.log('Error:', err);45 });46var chromy = new Chromy({ port: 9222, visible: true, waitTimeout: 5000, frame: true });47chromy.chain()48 .evaluate(function() {49 return document.querySelector('title').innerText;50 })51 .result(function(title) {52 console.log(title);53 })54 .end()55 .then(function() {56 console.log('Done');57 })58 .catch(function(err) {59 console.log('Error:', err);60 });

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run chromy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful