Best JavaScript code snippet using playwright-internal
mui.init.5+.js
Source:mui.init.5+.js
1/**2 * mui.init 5+3 * @param {type} $4 * @returns {undefined}5 */6(function($) {7 var defaultOptions = {8 swipeBack: false,9 preloadPages: [], //5+ lazyLoad webview10 preloadLimit: 10, //é¢å è½½çªå£çæ°ééå¶(ä¸æ¦è¶
åºï¼å
è¿å
åº)11 keyEventBind: {12 backbutton: true,13 menubutton: true14 },15 titleConfig: {16 height: "44px",17 backgroundColor: "#f7f7f7", //导èªæ èæ¯è²18 bottomBorderColor: "#cccccc", //åºé¨è¾¹çº¿é¢è²19 title: { //æ é¢é
ç½®20 text: "", //æ é¢æå21 position: {22 top: 0,23 left: 0,24 width: "100%",25 height: "100%"26 },27 styles: {28 color: "#000000",29 align: "center",30 family: "'Helvetica Neue',Helvetica,sans-serif",31 size: "17px",32 style: "normal",33 weight: "normal",34 fontSrc: ""35 }36 },37 back: {38 image: {39 base64Data: '',40 imgSrc: '',41 sprite: {42 top: '0px',43 left: '0px',44 width: '100%',45 height: '100%'46 },47 position: {48 top: "10px",49 left: "10px",50 width: "24px",51 height: "24px"52 }53 }54 }55 }56 };57 //é»è®¤é¡µé¢å¨ç»58 var defaultShow = {59 event:"titleUpdate",60 autoShow: true,61 duration: 300,62 aniShow: 'slide-in-right',63 extras:{}64 };65 //è¥æ§è¡äºæ¾ç¤ºå¨ç»åå§åæä½ï¼åè¦è¦çé»è®¤é
ç½®66 if($.options.show) {67 defaultShow = $.extend(true, defaultShow, $.options.show);68 }69 $.currentWebview = null;70 $.extend(true, $.global, defaultOptions);71 $.extend(true, $.options, defaultOptions);72 /**73 * çå¾
å¨ç»é
ç½®74 * @param {type} options75 * @returns {Object}76 */77 $.waitingOptions = function(options) {78 return $.extend(true, {}, {79 autoShow: true,80 title: '',81 modal: false82 }, options);83 };84 /**85 * çªå£æ¾ç¤ºé
ç½®86 * @param {type} options87 * @returns {Object}88 */89 $.showOptions = function(options) {90 return $.extend(true, {}, defaultShow, options);91 };92 /**93 * çªå£é»è®¤é
ç½®94 * @param {type} options95 * @returns {Object}96 */97 $.windowOptions = function(options) {98 return $.extend({99 scalable: false,100 bounce: "" //vertical101 }, options);102 };103 /**104 * plusReady105 * @param {type} callback106 * @returns {_L6.$}107 */108 $.plusReady = function(callback) {109 if(window.plus) {110 setTimeout(function() { //解å³callbackä¸plusreadyäºä»¶çæ§è¡æ¶æºé®é¢(å
¸åæ¡ä¾:showWaiting,closeWaiting)111 callback();112 }, 0);113 } else {114 document.addEventListener("plusready", function() {115 callback();116 }, false);117 }118 return this;119 };120 /**121 * 5+ event(5+没æä¾ä¹åæèªå·±å®ç°)122 * @param {type} webview123 * @param {type} eventType124 * @param {type} data125 * @returns {undefined}126 */127 $.fire = function(webview, eventType, data) {128 if(webview) {129 if(typeof data === 'undefined') {130 data = '';131 } else if(typeof data === 'boolean' || typeof data === 'number') {132 webview.evalJS("typeof mui!=='undefined'&&mui.receive('" + eventType + "'," + data + ")");133 return;134 } else if($.isPlainObject(data) || $.isArray(data)) {135 data = JSON.stringify(data || {}).replace(/\'/g, "\\u0027").replace(/\\/g, "\\u005c");136 }137 webview.evalJS("typeof mui!=='undefined'&&mui.receive('" + eventType + "','" + data + "')");138 }139 };140 /**141 * 5+ event(5+没æä¾ä¹åæèªå·±å®ç°)142 * @param {type} eventType143 * @param {type} data144 * @returns {undefined}145 */146 $.receive = function(eventType, data) {147 if(eventType) {148 try {149 if(data && typeof data === 'string') {150 data = JSON.parse(data);151 }152 } catch(e) {}153 $.trigger(document, eventType, data);154 }155 };156 var triggerPreload = function(webview) {157 if(!webview.preloaded) { //ä¿è¯ä»
触åä¸æ¬¡158 $.fire(webview, 'preload');159 var list = webview.children();160 for(var i = 0; i < list.length; i++) {161 $.fire(list[i], 'preload');162 }163 webview.preloaded = true;164 }165 };166 var trigger = function(webview, eventType, timeChecked) {167 if(timeChecked) {168 if(!webview[eventType + 'ed']) {169 $.fire(webview, eventType);170 var list = webview.children();171 for(var i = 0; i < list.length; i++) {172 $.fire(list[i], eventType);173 }174 webview[eventType + 'ed'] = true;175 }176 } else {177 $.fire(webview, eventType);178 var list = webview.children();179 for(var i = 0; i < list.length; i++) {180 $.fire(list[i], eventType);181 }182 }183 };184 /**185 * æå¼æ°çªå£186 * @param {string} url è¦æå¼ç页é¢å°å187 * @param {string} id æå®é¡µé¢ID188 * @param {object} options å¯é:åæ°,çå¾
,çªå£,æ¾ç¤ºé
ç½®{params:{},waiting:{},styles:{},show:{}}189 */190 $.openWindow = function(url, id, options) {191 if(typeof url === 'object') {192 options = url;193 url = options.url;194 id = options.id || url;195 } else {196 if(typeof id === 'object') {197 options = id;198 id = options.id || url;199 } else {200 id = id || url;201 }202 }203 if(!$.os.plus) {204 //TODO å
临æ¶è¿ä¹å¤çï¼ææºä¸é¡¶å±è·³ï¼PCä¸parentè·³205 if($.os.ios || $.os.android) {206 window.top.location.href = url;207 } else {208 window.parent.location.href = url;209 }210 return;211 }212 if(!window.plus) {213 return;214 }215 options = options || {};216 var params = options.params || {};217 var webview = null,218 webviewCache = null,219 nShow, nWaiting;220 if($.webviews[id]) {221 webviewCache = $.webviews[id];222 //webviewçå®åå¨ï¼æè½è·å223 if(plus.webview.getWebviewById(id)) {224 webview = webviewCache.webview;225 }226 } else if(options.createNew !== true) {227 webview = plus.webview.getWebviewById(id);228 }229 if(webview) { //å·²ç¼å230 //æ¯æ¬¡showé½éè¦ä¼ éå¨ç»åæ°ï¼231 //é¢å è½½çå¨ç»åæ°ä¼å
级ï¼openWindowé
ç½®>preloadPagesé
ç½®>muié»è®¤é
ç½®ï¼232 nShow = webviewCache ? webviewCache.show : defaultShow;233 nShow = options.show ? $.extend(nShow, options.show) : nShow;234 nShow.autoShow && webview.show(nShow.aniShow, nShow.duration, function() {235 triggerPreload(webview);236 trigger(webview, 'pagebeforeshow', false);237 });238 if(webviewCache) {239 webviewCache.afterShowMethodName && webview.evalJS(webviewCache.afterShowMethodName + '(\'' + JSON.stringify(params) + '\')');240 }241 return webview;242 } else { //æ°çªå£243 if(!url) {244 throw new Error('webview[' + id + '] does not exist');245 }246 //æ¾ç¤ºwaiting247 var waitingConfig = $.waitingOptions(options.waiting);248 if(waitingConfig.autoShow) {249 nWaiting = plus.nativeUI.showWaiting(waitingConfig.title, waitingConfig.options);250 }251 //å建页é¢252 options = $.extend(options, {253 id: id,254 url: url255 });256 webview = $.createWindow(options);257 //æ¾ç¤º258 nShow = $.showOptions(options.show);259 if(nShow.autoShow) {260 var showWebview = function() {261 //å
³éçå¾
æ¡262 if(nWaiting) {263 nWaiting.close();264 }265 //æ¾ç¤ºé¡µé¢266 webview.show(nShow.aniShow, nShow.duration, function() {},nShow.extras);267 options.afterShowMethodName && webview.evalJS(options.afterShowMethodName + '(\'' + JSON.stringify(params) + '\')');268 };269 //titleUpdate触åæ¶æºæ©äºloadedï¼æ´æ¢ä¸ºtitleUpdateåï¼å¯ä»¥æ´æ©çæ¾ç¤ºwebview270 webview.addEventListener(nShow.event, showWebview, false);271 //loadedäºä»¶åçåï¼è§¦åé¢å è½½åpagebeforeshowäºä»¶272 webview.addEventListener("loaded", function() {273 triggerPreload(webview);274 trigger(webview, 'pagebeforeshow', false);275 }, false);276 }277 }278 return webview;279 };280 $.openWindowWithTitle = function(options, titleConfig) {281 options = options || {};282 var url = options.url;283 var id = options.id || url;284 if(!$.os.plus) {285 //TODO å
临æ¶è¿ä¹å¤çï¼ææºä¸é¡¶å±è·³ï¼PCä¸parentè·³286 if($.os.ios || $.os.android) {287 window.top.location.href = url;288 } else {289 window.parent.location.href = url;290 }291 return;292 }293 if(!window.plus) {294 return;295 }296 var params = options.params || {};297 var webview = null,298 webviewCache = null,299 nShow, nWaiting;300 if($.webviews[id]) {301 webviewCache = $.webviews[id];302 //webviewçå®åå¨ï¼æè½è·å303 if(plus.webview.getWebviewById(id)) {304 webview = webviewCache.webview;305 }306 } else if(options.createNew !== true) {307 webview = plus.webview.getWebviewById(id);308 }309 if(webview) { //å·²ç¼å310 //æ¯æ¬¡showé½éè¦ä¼ éå¨ç»åæ°ï¼311 //é¢å è½½çå¨ç»åæ°ä¼å
级ï¼openWindowé
ç½®>preloadPagesé
ç½®>muié»è®¤é
ç½®ï¼312 nShow = webviewCache ? webviewCache.show : defaultShow;313 nShow = options.show ? $.extend(nShow, options.show) : nShow;314 nShow.autoShow && webview.show(nShow.aniShow, nShow.duration, function() {315 triggerPreload(webview);316 trigger(webview, 'pagebeforeshow', false);317 });318 if(webviewCache) {319 webviewCache.afterShowMethodName && webview.evalJS(webviewCache.afterShowMethodName + '(\'' + JSON.stringify(params) + '\')');320 }321 return webview;322 } else { //æ°çªå£323 if(!url) {324 throw new Error('webview[' + id + '] does not exist');325 }326 //æ¾ç¤ºwaiting327 var waitingConfig = $.waitingOptions(options.waiting);328 if(waitingConfig.autoShow) {329 nWaiting = plus.nativeUI.showWaiting(waitingConfig.title, waitingConfig.options);330 }331 //å建页é¢332 options = $.extend(options, {333 id: id,334 url: url335 });336 webview = $.createWindow(options);337 if(titleConfig) { //å¤çåç头338 $.extend(true, $.options.titleConfig, titleConfig);339 var tid = $.options.titleConfig.id ? $.options.titleConfig.id : id + "_title";340 var view = new plus.nativeObj.View(tid, {341 top: 0,342 height: $.options.titleConfig.height,343 width: "100%",344 dock: "top",345 position: "dock"346 });347 view.drawRect($.options.titleConfig.backgroundColor); //ç»å¶èæ¯è²348 var _b = parseInt($.options.titleConfig.height) - 1;349 view.drawRect($.options.titleConfig.bottomBorderColor, {350 top: _b + "px",351 left: "0px"352 }); //ç»å¶åºé¨è¾¹çº¿353 //ç»å¶æå354 if($.options.titleConfig.title.text){355 var _title = $.options.titleConfig.title;356 view.drawText(_title.text,_title.position , _title.styles);357 }358 359 //è¿åå¾æ ç»å¶360 var _back = $.options.titleConfig.back;361 var backClick = null;362 //ä¼å
åä½363 //å
¶æ¬¡æ¯å¾ç364 var _backImage = _back.image;365 if(_backImage.base64Data || _backImage.imgSrc) {366 //TODO æ¤å¤éè¦å¤çç¾åæ¯çæ
åµ367 backClick = {368 left:parseInt(_backImage.position.left),369 right:parseInt(_backImage.position.left) + parseInt(_backImage.position.width)370 };371 var bitmap = new plus.nativeObj.Bitmap(id + "_back");372 if(_backImage.base64Data) { //ä¼å
base64ç¼ç å符串373 bitmap.loadBase64Data(_backImage.base64Data);374 } else { //å
¶æ¬¡å è½½å¾çæ件375 bitmap.load(_backImage.imgSrc);376 }377 view.drawBitmap(bitmap,_backImage.sprite , _backImage.position);378 }379 //å¤çç¹å»äºä»¶380 view.setTouchEventRect({381 top: "0px",382 left: "0px",383 width: "100%",384 height: "100%"385 });386 view.interceptTouchEvent(true);387 view.addEventListener("click", function(e) {388 var x = e.clientX;389 390 //è¿åæé®ç¹å»391 if(backClick&& x > backClick.left && x < backClick.right){392 if( _back.click && $.isFunction(_back.click)){393 _back.click();394 }else{395 webview.evalJS("window.mui&&mui.back();");396 }397 }398 }, false);399 webview.append(view);400 }401 //æ¾ç¤º402 nShow = $.showOptions(options.show);403 if(nShow.autoShow) {404 //titleUpdate触åæ¶æºæ©äºloadedï¼æ´æ¢ä¸ºtitleUpdateåï¼å¯ä»¥æ´æ©çæ¾ç¤ºwebview405 webview.addEventListener(nShow.event, function () {406 //å
³éçå¾
æ¡407 if(nWaiting) {408 nWaiting.close();409 }410 //æ¾ç¤ºé¡µé¢411 webview.show(nShow.aniShow, nShow.duration, function() {},nShow.extras);412 }, false);413 }414 }415 return webview;416 };417 /**418 * æ ¹æ®é
置信æ¯å建ä¸ä¸ªwebview419 * @param {type} options420 * @param {type} isCreate421 * @returns {webview}422 */423 $.createWindow = function(options, isCreate) {424 if(!window.plus) {425 return;426 }427 var id = options.id || options.url;428 var webview;429 if(options.preload) {430 if($.webviews[id] && $.webviews[id].webview.getURL()) { //å·²ç»cache431 webview = $.webviews[id].webview;432 } else { //æ°å¢é¢å è½½çªå£433 //å¤ææ¯å¦æºå¸¦createNewåæ°ï¼é»è®¤ä¸ºfalse434 if(options.createNew !== true) {435 webview = plus.webview.getWebviewById(id);436 }437 //ä¹å没æï¼é£å°±æ°å建 438 if(!webview) {439 webview = plus.webview.create(options.url, id, $.windowOptions(options.styles), $.extend({440 preload: true441 }, options.extras));442 if(options.subpages) {443 $.each(options.subpages, function(index, subpage) {444 var subpageId = subpage.id || subpage.url;445 if(subpageId) { //è¿æ»¤ç©ºå¯¹è±¡446 var subWebview = plus.webview.getWebviewById(subpageId);447 if(!subWebview) { //å¦æ该webviewä¸åå¨ï¼åå建448 subWebview = plus.webview.create(subpage.url, subpageId, $.windowOptions(subpage.styles), $.extend({449 preload: true450 }, subpage.extras));451 }452 webview.append(subWebview);453 }454 });455 }456 }457 }458 //TODO ç论ä¸ï¼åwebviewä¹åºè¯¥è®¡ç®å°é¢å è½½éåä¸ï¼ä½è¿æ ·å°±éº»ç¦äºï¼è¦éå¿
é¡»éæ´ä½ï¼å¦åå¯è½åºç°é®é¢ï¼459 $.webviews[id] = {460 webview: webview, //ç®åä»
preloadçç¼åwebview461 preload: true,462 show: $.showOptions(options.show),463 afterShowMethodName: options.afterShowMethodName //å°±ä¸åºè¯¥ç¨evalJSãåºè¯¥æ¯éè¿äºä»¶æ¶æ¯é讯464 };465 //ç´¢å¼è¯¥é¢å è½½çªå£466 var preloads = $.data.preloads;467 var index = preloads.indexOf(id);468 if(~index) { //å é¤å·²åå¨ç(åç¸è°æ´æå
¥ä½ç½®)469 preloads.splice(index, 1);470 }471 preloads.push(id);472 if(preloads.length > $.options.preloadLimit) {473 //å
è¿å
åº474 var first = $.data.preloads.shift();475 var webviewCache = $.webviews[first];476 if(webviewCache && webviewCache.webview) {477 //éè¦å°èªå·±æå¼çææ页é¢ï¼å
¨é¨closeï¼478 //å
³é该é¢å è½½webview 479 $.closeAll(webviewCache.webview);480 }481 //å é¤ç¼å482 delete $.webviews[first];483 }484 } else {485 if(isCreate !== false) { //ç´æ¥å建éé¢å è½½çªå£486 webview = plus.webview.create(options.url, id, $.windowOptions(options.styles), options.extras);487 if(options.subpages) {488 $.each(options.subpages, function(index, subpage) {489 var subpageId = subpage.id || subpage.url;490 var subWebview = plus.webview.getWebviewById(subpageId);491 if(!subWebview) {492 subWebview = plus.webview.create(subpage.url, subpageId, $.windowOptions(subpage.styles), subpage.extras);493 }494 webview.append(subWebview);495 });496 }497 }498 }499 return webview;500 };501 /**502 * é¢å è½½503 */504 $.preload = function(options) {505 //è°ç¨é¢å è½½å½æ°ï¼ä¸ç®¡æ¯å¦ä¼ épreloadåæ°ï¼å¼ºå¶å为true506 if(!options.preload) {507 options.preload = true;508 }509 return $.createWindow(options);510 };511 /**512 *å
³éå½åwebviewæå¼çææwebviewï¼513 */514 $.closeOpened = function(webview) {515 var opened = webview.opened();516 if(opened) {517 for(var i = 0, len = opened.length; i < len; i++) {518 var openedWebview = opened[i];519 var open_open = openedWebview.opened();520 if(open_open && open_open.length > 0) {521 //å
³éæå¼çwebview522 $.closeOpened(openedWebview);523 //å
³éèªå·±524 openedWebview.close("none");525 } else {526 //å¦æç´æ¥å©åèç¹ï¼å°±ä¸ç¨å
³éäºï¼å 为ç¶å
³éçæ¶åï¼ä¼èªå¨å
³éåï¼527 if(openedWebview.parent() !== webview) {528 openedWebview.close('none');529 }530 }531 }532 }533 };534 $.closeAll = function(webview, aniShow) {535 $.closeOpened(webview);536 if(aniShow) {537 webview.close(aniShow);538 } else {539 webview.close();540 }541 };542 /**543 * æ¹éå建webview544 * @param {type} options545 * @returns {undefined}546 */547 $.createWindows = function(options) {548 $.each(options, function(index, option) {549 //åå§åé¢å è½½çªå£(å建)åéé¢å è½½çªå£(ä»
é
ç½®ï¼ä¸å建)550 $.createWindow(option, false);551 });552 };553 /**554 * å建å½å页é¢çåwebview555 * @param {type} options556 * @returns {webview}557 */558 $.appendWebview = function(options) {559 if(!window.plus) {560 return;561 }562 var id = options.id || options.url;563 var webview;564 if(!$.webviews[id]) { //ä¿è¯æ§è¡ä¸é565 //TODO è¿éä¹æéæ£ï¼æ¯å¦æ个webviewä¸æ¯ä½ä¸ºsubpageå建çï¼èæ¯ä½ä¸ºtarget webviewçè¯ï¼566 if(!plus.webview.getWebviewById(id)) {567 webview = plus.webview.create(options.url, id, options.styles, options.extras);568 }569 //ä¹åçå®ç°æ¹æ¡ï¼åçªå£loadedä¹ååappendå°ç¶çªå£ä¸ï¼570 //é®é¢ï¼é¨ååçªå£loadedäºä»¶åçè¾æï¼æ¤æ¶æ§è¡ç¶çªå£çchildrenæ¹æ³ä¼è¿å空ï¼å¯¼è´ç¶åé讯失败ï¼571 // æ¯å¦ç¶é¡µé¢æ§è¡å®preloadäºä»¶åï¼é触åå页é¢çpreloadäºä»¶ï¼æ¤æ¶æªappendçè¯ï¼å°±æ æ³è§¦åï¼572 //ä¿®æ¹æ¹å¼ï¼ä¸åçæ§loadedäºä»¶ï¼ç´æ¥append573 //by chb@20150521574 // webview.addEventListener('loaded', function() {575 plus.webview.currentWebview().append(webview);576 // });577 $.webviews[id] = options;578 }579 return webview;580 };581 //å
¨å±webviews582 $.webviews = {};583 //é¢å è½½çªå£ç´¢å¼584 $.data.preloads = [];585 //$.currentWebview586 $.plusReady(function() {587 $.currentWebview = plus.webview.currentWebview();588 });589 $.addInit({590 name: '5+',591 index: 100,592 handle: function() {593 var options = $.options;594 var subpages = options.subpages || [];595 if($.os.plus) {596 $.plusReady(function() {597 //TODO è¿ééè¦å¤æä¸ä¸ï¼æ好çåçªå£å è½½å®æ¯åï¼åè°ç¨ä¸»çªå£çshowæ¹æ³ï¼598 //æè
ï¼å¨openwindowæ¹æ³ä¸ï¼çå¬å®ç°ï¼599 $.each(subpages, function(index, subpage) {600 $.appendWebview(subpage);601 });602 //å¤ææ¯å¦é¦é¡µ603 if(plus.webview.currentWebview() === plus.webview.getWebviewById(plus.runtime.appid)) {604 //é¦é¡µéè¦èªå·±æ¿æ´»é¢å è½½ï¼605 //timeoutå 为å页é¢loadedä¹åæappendçï¼é²æ¢å页é¢å°æªappendãä»è导è´å
¶preloadæªè§¦åçé®é¢ï¼606 setTimeout(function() {607 triggerPreload(plus.webview.currentWebview());608 }, 300);609 }610 //设置ios顶é¨ç¶ææ é¢è²ï¼611 if($.os.ios && $.options.statusBarBackground) {612 plus.navigator.setStatusBarBackground($.options.statusBarBackground);613 }614 if($.os.android && parseFloat($.os.version) < 4.4) {615 //解å³Androidå¹³å°4.4çæ¬ä»¥ä¸ï¼resumeåï¼ç¶çªä½æ é¢å»¶è¿æ¸²æçé®é¢ï¼616 if(plus.webview.currentWebview().parent() == null) {617 document.addEventListener("resume", function() {618 var body = document.body;619 body.style.display = 'none';620 setTimeout(function() {621 body.style.display = '';622 }, 10);623 });624 }625 }626 });627 } else {628 //å·²æ¯æiframeåµå
¥629 // if (subpages.length > 0) {630 // var err = document.createElement('div');631 // err.className = 'mui-error';632 // //æåæè¿°633 // var span = document.createElement('span');634 // span.innerHTML = 'å¨è¯¥æµè§å¨ä¸ï¼ä¸æ¯æå建å页é¢ï¼å
·ä½åè';635 // err.appendChild(span);636 // var a = document.createElement('a');637 // a.innerHTML = '"muiæ¡æ¶éç¨åºæ¯"';638 // a.href = 'http://ask.dcloud.net.cn/article/113';639 // err.appendChild(a);640 // document.body.appendChild(err);641 // console.log('å¨è¯¥æµè§å¨ä¸ï¼ä¸æ¯æå建å页é¢');642 // }643 }644 }645 });646 window.addEventListener('preload', function() {647 //å¤çé¢å è½½é¨å648 var webviews = $.options.preloadPages || [];649 $.plusReady(function() {650 $.each(webviews, function(index, webview) {651 $.createWindow($.extend(webview, {652 preload: true653 }));654 });655 });656 });657 $.supportStatusbarOffset = function() {658 return $.os.plus && $.os.ios && parseFloat($.os.version) >= 7;659 };660 $.ready(function() {661 //æ è¯å½åç¯å¢æ¯æstatusbar662 if($.supportStatusbarOffset()) {663 document.body.classList.add($.className('statusbar'));664 }665 });...
mui.pullrefresh.5+.js
Source:mui.pullrefresh.5+.js
1/**2 * pullRefresh 5+3 * @param {type} $4 * @returns {undefined}5 */6(function($, document) {7 if (!($.os.plus)) { //ä»
å¨5+androidæ¯æå¤webviewç使ç¨8 return;9 }10 $.plusReady(function() {11 if (window.__NWin_Enable__ === false) { //ä¸æ¯æå¤webviewï¼åä¸ç¨5+ä¸æå·æ°12 return;13 }14 var CLASS_PLUS_PULLREFRESH = $.className('plus-pullrefresh');15 var CLASS_VISIBILITY = $.className('visibility');16 var CLASS_HIDDEN = $.className('hidden');17 var CLASS_BLOCK = $.className('block');18 var CLASS_PULL_CAPTION = $.className('pull-caption');19 var CLASS_PULL_CAPTION_DOWN = $.className('pull-caption-down');20 var CLASS_PULL_CAPTION_REFRESH = $.className('pull-caption-refresh');21 var CLASS_PULL_CAPTION_NOMORE = $.className('pull-caption-nomore');22 var PlusPullRefresh = $.Class.extend({23 init: function(element, options) {24 this.element = element;25 this.options = options;26 this.wrapper = this.scroller = element;27 this._init();28 this._initPulldownRefreshEvent();29 },30 _init: function() {31 var self = this;32 //document.addEventListener('plusscrollbottom', this);33 window.addEventListener('dragup', self);34 document.addEventListener("plusscrollbottom", self);35 self.scrollInterval = window.setInterval(function() {36 if (self.isScroll && !self.loading) {37 if (window.pageYOffset + window.innerHeight + 10 >= document.documentElement.scrollHeight) {38 self.isScroll = false; //æ¾å¨è¿éæ¯å 为快éæ»å¨çè¯ï¼æå¯è½æ£æµæ¶ï¼è¿æ²¡å°åºï¼æ以åªè¦ææ»å¨ï¼æ²¡å°åºä¹åä¸ç´æ£æµé«åº¦åå39 if (self.bottomPocket) {40 self.pullupLoading();41 }42 }43 }44 }, 100);45 },46 _initPulldownRefreshEvent: function() {47 var self = this;48 $.plusReady(function() {49 if(self.options.down.style == "circle"){50 //åwebviewãåç转å51 self.options.webview = plus.webview.currentWebview();52 self.options.webview.setPullToRefresh({53 support: true,54 color:self.options.down.color || '#2BD009',55 height: self.options.down.height || '50px',56 range: self.options.down.range || '100px',57 style: 'circle',58 offset: self.options.down.offset || '0px'59 }, function() {60 self.options.down.callback();61 });62 }else if (self.topPocket && self.options.webviewId) {63 var webview = plus.webview.getWebviewById(self.options.webviewId);//åçªå£64 if (!webview) {65 return;66 }67 self.options.webview = webview;68 var downOptions = self.options.down;69 var height = downOptions.height;70 webview.addEventListener('close', function() {71 var attrWebviewId = self.options.webviewId && self.options.webviewId.replace(/\//g, "_"); //æ¿æ¢ææ"/" 72 self.element.removeAttribute('data-pullrefresh-plus-' + attrWebviewId);73 });74 webview.addEventListener("dragBounce", function(e) {75 if (!self.pulldown) {76 self._initPulldownRefresh();77 } else {78 self.pullPocket.classList.add(CLASS_BLOCK);79 }80 switch (e.status) {81 case "beforeChangeOffset": //ä¸æå¯å·æ°ç¶æ82 self._setCaption(downOptions.contentdown);83 break;84 case "afterChangeOffset": //æ¾å¼å¯å·æ°ç¶æ85 self._setCaption(downOptions.contentover);86 break;87 case "dragEndAfterChangeOffset": //æ£å¨å·æ°ç¶æ88 //æ§è¡ä¸æå·æ°æå¨webviewçåè°å½æ°89 webview.evalJS("window.mui&&mui.options.pullRefresh.down.callback()");90 self._setCaption(downOptions.contentrefresh);91 break;92 default:93 break;94 }95 }, false);96 97 webview.setBounce({98 position: {99 top: height * 2 + 'px'100 },101 changeoffset: {102 top: height + 'px'103 }104 });105 106 }107 });108 },109 handleEvent: function(e) {110 var self = this;111 if (self.stopped) {112 return;113 }114 self.isScroll = false;115 if (e.type === 'dragup' || e.type === 'plusscrollbottom') {116 self.isScroll = true;117 setTimeout(function() {118 self.isScroll = false;119 }, 1000);120 }121 }122 }).extend($.extend({123 setStopped: function(stopped) { //该æ¹æ³æ¯å页é¢è°ç¨ç124 this.stopped = !!stopped;125 //TODO æ¤å¤éè¦è®¾ç½®å½åwebviewçbounce为none,ç®å5+æBUG126 var webview = plus.webview.currentWebview();127 if (this.stopped) {128 webview.setStyle({129 bounce: 'none'130 });131 webview.setBounce({132 position: {133 top: 'none'134 }135 });136 } else {137 var height = this.options.down.height;138 webview.setStyle({139 bounce: 'vertical'140 });141 webview.setBounce({142 position: {143 top: height * 2 + 'px'144 },145 changeoffset: {146 top: height + 'px'147 }148 });149 }150 },151 beginPulldown:function() { 152 var self = this;153 $.plusReady(function() {154 //è¿é延æ¶çç®çæ¯ä¸ºäºä¿è¯ä¸æå·æ°ç»ä»¶åå§åå®æï¼åç»åºè¯¥åææç¶æç155 setTimeout(function () {156 if(self.options.down.style == "circle"){//åwebviewä¸æå·æ°157 plus.webview.currentWebview().beginPullToRefresh();158 }else{//åwebview模å¼159 var webview = self.options.webview;160 if(webview){161 webview.setBounce({162 offset: {163 top: self.options.down.height + "px"164 }165 });166 }167 }168 },15);169 }.bind(this));170 },171 pulldownLoading: function () {//该æ¹æ³æ¯å页é¢è°ç¨çï¼å
¼å®¹èçåå²API172 this.beginPulldown();173 },174 _pulldownLoading: function() { //该æ¹æ³æ¯ç¶é¡µé¢è°ç¨ç175 var self = this;176 $.plusReady(function() {177 var childWebview = plus.webview.getWebviewById(self.options.webviewId);178 childWebview && childWebview.setBounce({179 offset: {180 top: self.options.down.height + "px"181 }182 });183 });184 },185 endPulldown:function(){186 var _wv = plus.webview.currentWebview();187 //åwebviewçä¸æå·æ°ï¼éè¦ä¿®æ¹ç¶çªå£æ示信æ¯188 if(_wv.parent() && this.options.down.style !== "circle"){189 _wv.parent().evalJS("mui&&mui(document.querySelector('.mui-content')).pullRefresh('" + JSON.stringify({190 webviewId: _wv.id191 }) + "')._endPulldownToRefresh()");192 }else{193 _wv.endPullToRefresh();194 }195 },196 endPulldownToRefresh: function () {//该æ¹æ³æ¯å页é¢è°ç¨çï¼å
¼å®¹èçåå²API197 this.endPulldown();198 }, 199 _endPulldownToRefresh: function() { //该æ¹æ³æ¯ç¶é¡µé¢è°ç¨ç200 var self = this;201 if (self.topPocket && self.options.webview) {202 self.options.webview.endPullToRefresh(); //ä¸æå·æ°æå¨webviewåå¼¹203 self.loading = false;204 self._setCaption(self.options.down.contentdown, true);205 setTimeout(function() {206 self.loading || self.topPocket.classList.remove(CLASS_BLOCK);207 }, 350);208 }209 },210 beginPullup:function(callback) {//å¼å§ä¸æå è½½211 var self = this;212 if (self.isLoading) return;213 self.isLoading = true;214 if (self.pulldown !== false) {215 self._initPullupRefresh();216 } else {217 this.pullPocket.classList.add(CLASS_BLOCK);218 }219 setTimeout(function() {220 self.pullLoading.classList.add(CLASS_VISIBILITY);221 self.pullLoading.classList.remove(CLASS_HIDDEN);222 self.pullCaption.innerHTML = ''; //ä¿®æ£5+é边第ä¸æ¬¡å è½½æ¶ï¼æåæ¾ç¤ºçbug(è¿ä¼æ¾ç¤ºåºæ¥ä¸ªâå¤â,çæµåºè¯¥æ¯æ¸²æé®é¢å¯¼è´ç)223 self.pullCaption.className = CLASS_PULL_CAPTION + ' ' + CLASS_PULL_CAPTION_REFRESH;224 self.pullCaption.innerHTML = self.options.up.contentrefresh;225 callback = callback || self.options.up.callback;226 callback && callback.call(self);227 }, 300);228 },229 pullupLoading:function (callback) {//å
¼å®¹èçAPI230 this.beginPullup(callback);231 },232 endPullup:function(finished) {//ä¸æå è½½ç»æ233 var self = this;234 if (self.pullLoading) {235 self.pullLoading.classList.remove(CLASS_VISIBILITY);236 self.pullLoading.classList.add(CLASS_HIDDEN);237 self.isLoading = false;238 if (finished) {239 self.finished = true;240 self.pullCaption.className = CLASS_PULL_CAPTION + ' ' + CLASS_PULL_CAPTION_NOMORE;241 self.pullCaption.innerHTML = self.options.up.contentnomore;242 //åæ¶5+çplusscrollbottomäºä»¶243 document.removeEventListener('plusscrollbottom', self);244 window.removeEventListener('dragup', self);245 } else { //åå§åæ¶éèï¼åç»ä¸åéè246 self.pullCaption.className = CLASS_PULL_CAPTION + ' ' + CLASS_PULL_CAPTION_DOWN;247 self.pullCaption.innerHTML = self.options.up.contentdown;248 }249 }250 },251 endPullupToRefresh: function (finished) {//ä¸æå è½½ç»æï¼å
¼å®¹èçAPI252 this.endPullup(finished);253 },254 disablePullupToRefresh: function() {255 this._initPullupRefresh();256 this.bottomPocket.className = $.className('pull-bottom-pocket') + ' ' + CLASS_HIDDEN;257 window.removeEventListener('dragup', this);258 },259 enablePullupToRefresh: function() {260 this._initPullupRefresh();261 this.bottomPocket.classList.remove(CLASS_HIDDEN);262 this.pullCaption.className = CLASS_PULL_CAPTION + ' ' + CLASS_PULL_CAPTION_DOWN;263 this.pullCaption.innerHTML = this.options.up.contentdown;264 document.addEventListener("plusscrollbottom", this);265 window.addEventListener('dragup', this);266 },267 scrollTo: function(x, y, time) {268 $.scrollTo(y, time);269 },270 scrollToBottom: function(time) {271 $.scrollTo(document.documentElement.scrollHeight, time);272 },273 refresh: function(isReset) {274 if (isReset && this.finished) {275 this.enablePullupToRefresh();276 this.finished = false;277 }278 }279 }, $.PullRefresh));280 //override h5 pullRefresh281 $.fn.pullRefresh_native = function(options) {282 var self;283 if (this.length === 0) {284 self = document.createElement('div');285 self.className = 'mui-content';286 document.body.appendChild(self);287 } else {288 self = this[0];289 }290 var args = options;291 //ä¸ä¸ªç¶éè¦æ¯æå¤ä¸ªåä¸æå·æ°292 options = options || {}293 if (typeof options === 'string') {294 options = $.parseJSON(options);295 };296 !options.webviewId && (options.webviewId = (plus.webview.currentWebview().id || plus.webview.currentWebview().getURL()));297 var pullRefreshApi = null;298 var attrWebviewId = options.webviewId && options.webviewId.replace(/\//g, "_"); //æ¿æ¢ææ"/"299 var id = self.getAttribute('data-pullrefresh-plus-' + attrWebviewId);300 if (!id && typeof args === 'undefined') {301 return false;302 }303 if (!id) { //é¿å
éå¤åå§å5+ pullrefresh304 id = ++$.uuid;305 self.setAttribute('data-pullrefresh-plus-' + attrWebviewId, id);306 document.body.classList.add(CLASS_PLUS_PULLREFRESH);307 $.data[id] = pullRefreshApi = new PlusPullRefresh(self, options);308 } else {309 pullRefreshApi = $.data[id];310 }311 if (options.down && options.down.auto) { //å¦æ设置äºautoï¼åèªå¨ä¸æä¸æ¬¡312 //pullRefreshApi._pulldownLoading(); //parent webview313 pullRefreshApi.beginPulldown();314 } else if (options.up && options.up.auto) { //å¦æ设置äºautoï¼åèªå¨ä¸æä¸æ¬¡315 pullRefreshApi.beginPullup();316 }317 return pullRefreshApi;318 };319 });...
dynamicWebviewEditorOverlay.js
Source:dynamicWebviewEditorOverlay.js
1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {6 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;7 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);8 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;9 return c > 3 && r && Object.defineProperty(target, key, r), r;10};11var __param = (this && this.__param) || function (paramIndex, decorator) {12 return function (target, key) { decorator(target, key, paramIndex); }13};14define(["require", "exports", "vs/base/common/decorators", "vs/base/common/event", "vs/base/common/lifecycle", "vs/platform/contextkey/common/contextkey", "vs/workbench/contrib/webview/browser/webview", "vs/platform/layout/browser/layoutService"], function (require, exports, decorators_1, event_1, lifecycle_1, contextkey_1, webview_1, layoutService_1) {15 "use strict";16 Object.defineProperty(exports, "__esModule", { value: true });17 exports.DynamicWebviewEditorOverlay = void 0;18 /**19 * Webview editor overlay that creates and destroys the underlying webview as needed.20 */21 let DynamicWebviewEditorOverlay = class DynamicWebviewEditorOverlay extends lifecycle_1.Disposable {22 constructor(id, initialOptions, initialContentOptions, extension, _layoutService, _webviewService, _contextKeyService) {23 super();24 this.id = id;25 this.extension = extension;26 this._layoutService = _layoutService;27 this._webviewService = _webviewService;28 this._contextKeyService = _contextKeyService;29 this._onDidWheel = this._register(new event_1.Emitter());30 this.onDidWheel = this._onDidWheel.event;31 this._pendingMessages = new Set();32 this._webview = this._register(new lifecycle_1.MutableDisposable());33 this._webviewEvents = this._register(new lifecycle_1.DisposableStore());34 this._html = '';35 this._initialScrollProgress = 0;36 this._state = undefined;37 this._owner = undefined;38 this._scopedContextKeyService = this._register(new lifecycle_1.MutableDisposable());39 this._onDispose = this._register(new event_1.Emitter());40 this.onDispose = this._onDispose.event;41 this._onDidFocus = this._register(new event_1.Emitter());42 this.onDidFocus = this._onDidFocus.event;43 this._onDidBlur = this._register(new event_1.Emitter());44 this.onDidBlur = this._onDidBlur.event;45 this._onDidClickLink = this._register(new event_1.Emitter());46 this.onDidClickLink = this._onDidClickLink.event;47 this._onDidReload = this._register(new event_1.Emitter());48 this.onDidReload = this._onDidReload.event;49 this._onDidScroll = this._register(new event_1.Emitter());50 this.onDidScroll = this._onDidScroll.event;51 this._onDidUpdateState = this._register(new event_1.Emitter());52 this.onDidUpdateState = this._onDidUpdateState.event;53 this._onMessage = this._register(new event_1.Emitter());54 this.onMessage = this._onMessage.event;55 this._onMissingCsp = this._register(new event_1.Emitter());56 this.onMissingCsp = this._onMissingCsp.event;57 this._options = initialOptions;58 this._contentOptions = initialContentOptions;59 this._findWidgetVisible = webview_1.KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_VISIBLE.bindTo(_contextKeyService);60 }61 dispose() {62 this.container.remove();63 this._onDispose.fire();64 super.dispose();65 }66 get container() {67 const container = document.createElement('div');68 container.id = `webview-${this.id}`;69 container.style.visibility = 'hidden';70 // Webviews cannot be reparented in the dom as it will destory their contents.71 // Mount them to a high level node to avoid this.72 this._layoutService.container.appendChild(container);73 return container;74 }75 claim(owner) {76 this._owner = owner;77 this.show();78 }79 release(owner) {80 if (this._owner !== owner) {81 return;82 }83 this._owner = undefined;84 this.container.style.visibility = 'hidden';85 if (!this._options.retainContextWhenHidden) {86 this._webview.clear();87 this._webviewEvents.clear();88 }89 }90 layoutWebviewOverElement(element, dimension) {91 if (!this.container || !this.container.parentElement) {92 return;93 }94 const frameRect = element.getBoundingClientRect();95 const containerRect = this.container.parentElement.getBoundingClientRect();96 this.container.style.position = 'absolute';97 this.container.style.top = `${frameRect.top - containerRect.top}px`;98 this.container.style.left = `${frameRect.left - containerRect.left}px`;99 this.container.style.width = `${dimension ? dimension.width : frameRect.width}px`;100 this.container.style.height = `${dimension ? dimension.height : frameRect.height}px`;101 }102 show() {103 if (!this._webview.value) {104 const webview = this._webviewService.createWebviewElement(this.id, this._options, this._contentOptions, this.extension);105 this._webview.value = webview;106 webview.state = this._state;107 if (this._html) {108 webview.html = this._html;109 }110 if (this._options.tryRestoreScrollPosition) {111 webview.initialScrollProgress = this._initialScrollProgress;112 }113 webview.mountTo(this.container);114 this._scopedContextKeyService.value = this._contextKeyService.createScoped(this.container);115 this._findWidgetVisible = webview_1.KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_VISIBLE.bindTo(this._scopedContextKeyService.value);116 // Forward events from inner webview to outer listeners117 this._webviewEvents.clear();118 this._webviewEvents.add(webview.onDidFocus(() => { this._onDidFocus.fire(); }));119 this._webviewEvents.add(webview.onDidBlur(() => { this._onDidBlur.fire(); }));120 this._webviewEvents.add(webview.onDidClickLink(x => { this._onDidClickLink.fire(x); }));121 this._webviewEvents.add(webview.onMessage(x => { this._onMessage.fire(x); }));122 this._webviewEvents.add(webview.onMissingCsp(x => { this._onMissingCsp.fire(x); }));123 this._webviewEvents.add(webview.onDidWheel(x => { this._onDidWheel.fire(x); }));124 this._webviewEvents.add(webview.onDidReload(() => { this._onDidReload.fire(); }));125 this._webviewEvents.add(webview.onDidScroll(x => {126 this._initialScrollProgress = x.scrollYPercentage;127 this._onDidScroll.fire(x);128 }));129 this._webviewEvents.add(webview.onDidUpdateState(state => {130 this._state = state;131 this._onDidUpdateState.fire(state);132 }));133 this._pendingMessages.forEach(msg => webview.postMessage(msg));134 this._pendingMessages.clear();135 }136 this.container.style.visibility = 'visible';137 }138 get html() { return this._html; }139 set html(value) {140 this._html = value;141 this.withWebview(webview => webview.html = value);142 }143 get initialScrollProgress() { return this._initialScrollProgress; }144 set initialScrollProgress(value) {145 this._initialScrollProgress = value;146 this.withWebview(webview => webview.initialScrollProgress = value);147 }148 get state() { return this._state; }149 set state(value) {150 this._state = value;151 this.withWebview(webview => webview.state = value);152 }153 get options() { return this._options; }154 set options(value) { this._options = Object.assign({ customClasses: this._options.customClasses }, value); }155 get contentOptions() { return this._contentOptions; }156 set contentOptions(value) {157 this._contentOptions = value;158 this.withWebview(webview => webview.contentOptions = value);159 }160 set localResourcesRoot(resources) {161 this.withWebview(webview => webview.localResourcesRoot = resources);162 }163 postMessage(data) {164 if (this._webview.value) {165 this._webview.value.postMessage(data);166 }167 else {168 this._pendingMessages.add(data);169 }170 }171 focus() { this.withWebview(webview => webview.focus()); }172 reload() { this.withWebview(webview => webview.reload()); }173 selectAll() { this.withWebview(webview => webview.selectAll()); }174 showFind() {175 if (this._webview.value) {176 this._webview.value.showFind();177 this._findWidgetVisible.set(true);178 }179 }180 hideFind() {181 var _a;182 this._findWidgetVisible.reset();183 (_a = this._webview.value) === null || _a === void 0 ? void 0 : _a.hideFind();184 }185 runFindAction(previous) { this.withWebview(webview => webview.runFindAction(previous)); }186 getInnerWebview() {187 return this._webview.value;188 }189 withWebview(f) {190 if (this._webview.value) {191 f(this._webview.value);192 }193 }194 windowDidDragStart() {195 this.withWebview(webview => webview.windowDidDragStart());196 }197 windowDidDragEnd() {198 this.withWebview(webview => webview.windowDidDragEnd());199 }200 };201 __decorate([202 decorators_1.memoize203 ], DynamicWebviewEditorOverlay.prototype, "container", null);204 DynamicWebviewEditorOverlay = __decorate([205 __param(4, layoutService_1.ILayoutService),206 __param(5, webview_1.IWebviewService),207 __param(6, contextkey_1.IContextKeyService)208 ], DynamicWebviewEditorOverlay);209 exports.DynamicWebviewEditorOverlay = DynamicWebviewEditorOverlay;210});...
webview.js
Source:webview.js
1/*2 * Copyright 2012 Research In Motion Limited.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16var networkResourceRequested = require('./webkitHandlers/networkResourceRequested'),17 utils = require('./utils'),18 config = require('./config'),19 webkitOriginAccess = require("./policy/webkitOriginAccess"),20 CHROME_HEIGHT = 0,21 OUT_OF_PROCESS = 1,22 webview,23 _webviewObj;24webview =25 {26 create: function (ready) {27 _webviewObj = window.qnx.webplatform.createWebView({processId: OUT_OF_PROCESS, defaultSendEventHandlers: ['onChooseFile', 'onOpenWindow'], defaultWebEventHandlers: ['InvokeRequestEvent']}, function () {28 //Create webkit event handlers29 var requestObj = networkResourceRequested.createHandler(_webviewObj);30 //Bind networkResourceRequested event so that everything works31 _webviewObj.onNetworkResourceRequested = requestObj.networkResourceRequestedHandler;32 webkitOriginAccess.addWebView(_webviewObj);33 _webviewObj.visible = true;34 _webviewObj.active = true;35 _webviewObj.zOrder = 0;36 _webviewObj.setGeometry(0, CHROME_HEIGHT, screen.width, screen.height - CHROME_HEIGHT);37 if (typeof config.backgroundColor !== 'undefined') {38 _webviewObj.backgroundColor = config.backgroundColor;39 }40 if (typeof config.customHeaders !== 'undefined') {41 _webviewObj.extraHttpHeaders = config.customHeaders;42 }43 if (typeof config.userAgent !== 'undefined') {44 _webviewObj.userAgent = config.userAgent;45 }46 _webviewObj.autoDeferNetworkingAndJavaScript = config.autoDeferNetworkingAndJavaScript;47 /* Catch and trigger our custom HTML dialog */48 _webviewObj.allowWebEvent("DialogRequested");49 _webviewObj.addEventListener("DocumentLoadFinished", function () {50 // show app window if auto hide splash screen is true, OR splash screen is not specified51 // if auto hide is set to false explicitly but no splash screen is specified, should still show app window52 // otherwise the app cannot be launched53 if (config.autoHideSplashScreen || !config["rim:splash"]) {54 window.qnx.webplatform.getApplication().windowVisible = true;55 }56 });57 if (ready && typeof ready === 'function') {58 ready();59 }60 window.qnx.webplatform.getController().dispatchEvent("webview.initialized", [_webviewObj]);61 // If content is not loaded, too bad open the visibility up.62 setTimeout(function () {63 if (config.autoHideSplashScreen || !config["rim:splash"]) {64 window.qnx.webplatform.getApplication().windowVisible = true;65 }66 }, 2500);67 });68 },69 destroy: function () {70 _webviewObj.destroy();71 },72 setURL: function (url) {73 _webviewObj.url = url;74 },75 reload: function () {76 _webviewObj.reload();77 },78 executeJavascript: function (js) {79 _webviewObj.executeJavaScript(js);80 },81 addEventListener: function (eventName, callback) {82 _webviewObj.addEventListener(eventName, callback);83 },84 removeEventListener: function (eventName, callback) {85 _webviewObj.removeEventListener(eventName, callback);86 },87 windowGroup: function () {88 return _webviewObj.windowGroup;89 },90 getGeometry: function () {91 return this.geometry;92 },93 setGeometry: function (x, y, width, height) {94 this.geometry = {x: x, y: y, w: width, h: height};95 _webviewObj.setGeometry(x, y, width, height);96 },97 setApplicationOrientation: function (angle) {98 _webviewObj.setApplicationOrientation(angle);99 },100 setExtraPluginDirectory: function (directory) {101 _webviewObj.setExtraPluginDirectory(directory);102 },103 setEnablePlugins: function (enablePlugins) {104 _webviewObj.pluginsEnabled = enablePlugins;105 },106 getEnablePlugins: function () {107 return _webviewObj.pluginsEnabled;108 },109 notifyApplicationOrientationDone: function () {110 _webviewObj.notifyApplicationOrientationDone();111 },112 setSandbox: function (sandbox) {113 _webviewObj.setFileSystemSandbox = sandbox;114 },115 getSandbox: function () {116 return _webviewObj.setFileSystemSandbox;117 },118 downloadURL: function (url) {119 _webviewObj.downloadURL(url);120 },121 handleContextMenuResponse: function (action) {122 _webviewObj.handleContextMenuResponse(action);123 },124 allowGeolocation : function (url) {125 _webviewObj.allowGeolocation(url);126 },127 disallowGeolocation : function (url) {128 _webviewObj.disallowGeolocation(url);129 },130 addKnownSSLCertificate: function (url, certificateInfo) {131 _webviewObj.addKnownSSLCertificate(url, certificateInfo);132 },133 continueSSLHandshaking: function (streamId, SSLAction) {134 _webviewObj.continueSSLHandshaking(streamId, SSLAction);135 },136 getSensitivity: function () {137 return _webviewObj.getSensitivity();138 },139 setSensitivity: function (sensitivity) {140 return _webviewObj.setSensitivity(sensitivity);141 },142 getBackgroundColor: function () {143 return _webviewObj.getBackgroundColor();144 },145 setBackgroundColor: function (backgroundColor) {146 return _webviewObj.setBackgroundColor(backgroundColor);147 },148 getWebViewObj: function (webview) {149 return _webviewObj;150 },151 setUIWebViewObj: function (webviewObj) {152 _webviewObj.uiWebView = webviewObj;153 },154 allowUserMedia: function (evtId, cameraName) {155 _webviewObj.allowUserMedia(evtId, cameraName);156 },157 disallowUserMedia: function (evtId) {158 _webviewObj.disallowUserMedia(evtId);159 }160};161webview.__defineGetter__('id', function () {162 if (_webviewObj) {163 return _webviewObj.id;164 }165});166webview.__defineGetter__('enableCrossSiteXHR', function () {167 return _webviewObj.enableCrossSiteXHR;168});169webview.__defineSetter__('enableCrossSiteXHR', function (shouldEnable) {170 _webviewObj.enableCrossSiteXHR = !!shouldEnable;171});172webview.__defineGetter__('processId', function () {173 return _webviewObj.processId;174});175webview.__defineSetter__('onOpenWindow', function (input) {176 _webviewObj.onOpenWindow = input;177});178webview.__defineSetter__('onCloseWindow', function (input) {179 _webviewObj.onCloseWindow = input;180});181webview.__defineSetter__('onDestroyWindow', function (input) {182 _webviewObj.onDestroyWindow = input;183});184webview.__defineSetter__('onDialogRequested', function (input) {185 _webviewObj.onDialogRequested = input;186});187webview.__defineSetter__('onGeolocationPermissionRequest', function (input) {188 _webviewObj.onGeolocationPermissionRequest = input;189});190webview.__defineSetter__('onSSLHandshakingFailed', function (input) {191 _webviewObj.onSSLHandshakingFailed = input;192});193webview.__defineSetter__('onPropertyCurrentContextEvent', function (input) {194 _webviewObj.onPropertyCurrentContextEvent = input;195});196webview.__defineSetter__('onContextMenuRequestEvent', function (input) {197 _webviewObj.onContextMenuRequestEvent = input;198});199webview.__defineSetter__('onContextMenuCancelEvent', function (input) {200 _webviewObj.onContextMenuCancelEvent = input;201});202webview.__defineSetter__('onUserMediaRequest', function (input) {203 _webviewObj.onUserMediaRequest = input;204});205webview.__defineSetter__('onChildWindowOpen', function (input) {206 _webviewObj.onChildWindowOpen = input;207});...
webviewGroup.js
Source:webviewGroup.js
1var webviewGroup = function(id, options) {2 this.id = id;3 this.options = options;4 this.styles = options.styles;5 this.items = options.items;6 this.onChange = options.onChange7 this.options.index = options.index || 0;8 this.webviews = {};9 this.webviewContexts = {};10 this.currentWebview = false;11 this._init();12};13var proto = webviewGroup.prototype;14proto._init = function() {15 this._initParent();16 this._initNativeView();17 this._initWebviewContexts(this.options.index);18};19proto._initParent = function() {20 this.parent = plus.webview.getWebviewById(this.id);21 if(!this.parent) {22 this.parent = plus.webview.create(this.id, this.id);23 this.parent.show('none');24 }25};26proto._initNativeView = function() {27 this.nativeView = new plus.nativeObj.View('__MUI_TAB_NATIVE', {28 'top': '83px',//è¿ä¸ªéè¦æ ¹æ®é¡¶é¨å¯¼èªå顶é¨é项å¡é«åº¦èªå¨è°æ´29 'height': (window.screen.height - 83)+"px",30 'left': '100%',31 'width': '100%',32 "backgroundColor":"#ffffff"33 });34 this.nativeView.show();35};36proto._initWebviewContexts = function() {37 for(var len = this.items.length, i = len - 1; i >= 0; i--) {38 var webviewOptions = this.items[i];39 var id = webviewOptions.id;40 var isFirst = i === 0;41 var isLast = i === (len - 1);42 var isCurrent = this.options.index === i;43 var extras = webviewOptions.extras;44 extras.__mui_url = webviewOptions.url;45 extras.__mui_index = i;46 extras.__mui_left = isFirst ? '' : this.items[i - 1].id;47 extras.__mui_right = isLast ? '' : this.items[i + 1].id;48 var styles = webviewOptions.styles || {};49 if(i > this.options.index) {50 styles.left = '100%';51 } else if(i < this.options.index) {52 styles.left = '-100%';53 } else {54 styles.left = '0';55 }56 var webviewContext = new webviewGroupContext(id, webviewOptions, this);57 this.webviewContexts[id] = webviewContext;58 if(isCurrent) {59 webviewContext.webview = plus.webview.getWebviewById(id);60 webviewContext.createWebview();61 webviewContext.webview.show("none");62 this._initDrags(webviewContext.webview);63 this.currentWebview = webviewContext.webview;64 }65 }66};67proto._onChange = function(webview) {68 this.currentWebview = webview;69 this.onChange({70 index: webview.__mui_index71 });72};73proto._dragCallback = function(dir, fromWebview, view, viewId) {74 if(view === this.nativeView) { //éè¦å建webview75 //第ä¸æ¥:åå§åç®æ webview76 this.webviewContexts[viewId].createWebview('drag');77 var targetWebview = this.webviewContexts[viewId].webview;78 targetWebview.show();79 this.nativeView.setStyle({80 left: '100%'81 });82 //第äºæ¥:åå§åç®æ webviewçdrag83 this._initDrags(targetWebview);84 this._onChange(targetWebview);85 //第ä¸æ¥:æ ¡éªç®æ webviewçå·¦å³webviewçdragåå§å86 this._checkDrags(targetWebview);87 } else {88 this._onChange(view);89 }90};91proto._initDrag = function(webview, dir) {92 var flag = ('__mui_drag_' + dir + '_flag');93 if(webview[flag]) {94 return;95 }96 var viewId = webview['__mui_' + (dir === 'left' ? 'right' : 'left')];97 if(viewId) {98 var view = plus.webview.getWebviewById(viewId);99 if(!view) { //å¦æç®æ webviewä¸åå¨,使ç¨nativeViewæ¿æ¢100 view = this.nativeView;101 } else {102 webview[flag] = true;103 }104 webview.drag({105 'direction': dir,106 'moveMode': 'followFinger'107 }, {108 'view': view,109 'moveMode': 'follow'110 },111 function(res) {112 if(res.type === 'end' && res.result) { //ææ½å®æ113 this._dragCallback(dir, webview, view, viewId);114 }115 }.bind(this)116 )117 } else {118 webview[flag] = true;119 }120};121proto._initDrags = function(webview) {122 this._initDrag(webview, 'left');123 this._initDrag(webview, 'right');124};125proto._checkDrags = function(webview) {126 var left = webview.__mui_left;127 var right = webview.__mui_right;128 if(left) {129 var leftWebview = plus.webview.getWebviewById(left);130 if(leftWebview && !leftWebview.__mui_drag_left_flag) {131 this._initDrag(leftWebview, 'left');132 }133 }134 if(right) {135 var rightWebview = plus.webview.getWebviewById(right);136 if(rightWebview && !rightWebview.__mui_drag_right_flag) {137 this._initDrag(rightWebview, 'right');138 }139 }140};141proto.getCurrentWebview = function() {142 return this.currentWebview;143};144proto.getCurrentWebviewContext = function() {145 if(this.currentWebview) {146 return this.webviewContexts[this.currentWebview.id];147 }148 return false;149};150proto.switchTab = function(id) {151 id = id.replace('_0', ''); //é¦é¡µéè¦æ¿æ¢ä¸ºappid152 var fromWebview = this.currentWebview;153 if(id === fromWebview.id) {154 return;155 }156 var toWebviewContext = this.webviewContexts[id];157 var toWebview = toWebviewContext.webview;158 var fromToLeft = '100%';159 var toFromLeft = '-100%';160 if(toWebviewContext.options.extras.__mui_index > fromWebview.__mui_index) {161 fromToLeft = '-100%';162 toFromLeft = '100%';163 }164 var isNew = false;165 if(!toWebview) {166 isNew = true;167 toWebviewContext.createWebview('startAnimation');168 toWebview = toWebviewContext.webview;169 // toWebview.showBehind(plus.webview.getSecondWebview());170 toWebview.show();171 this._initDrags(toWebview);172 this._checkDrags(toWebview); //æ°å»ºçæ¶ååéæ ¡éª173 }174 var self = this;175// console.log("current:" + fromWebview.id + ",to:" + fromToLeft);176// console.log("next:" + toWebview.id + ",from:" + toFromLeft);177 plus.webview.startAnimation({178 'view': fromWebview,179 'styles': {180 'fromLeft': '0',181 'toLeft': fromToLeft182 },183 'action': 'show'184 }, {185 'view': toWebview,186 'styles': {187 'fromLeft': toFromLeft,188 'toLeft': '0'189 },190 'action': 'show'191 },192 function(e) {193 //console.log("startAnimation callback...");194 if(e.id === toWebview.id) {195 isNew && plus.nativeUI.showWaiting();196 this.currentWebview = toWebview;197 this.onChange({198 index: toWebview.__mui_index199 });200 }201 }.bind(this)202 )203};204/**205 * @param {Object} id206 * @param {Object} webviewOptions207 */208var webviewGroupContext = function(id, webviewOptions, groupContext) {209 this.id = id;210 this.url = webviewOptions.url;211 this.options = webviewOptions;212 this.groupContext = groupContext;213 this.webview = false;214 this.inited = false;215};216var _proto = webviewGroupContext.prototype;217_proto.createWebview = function(from) {218 var options = this.options;219 options.styles = options.styles || {220 top: "83px",221 bottom: "0px",222 render: "always"223 };224 options.styles.popGesture = 'none';225 if(this.webview) {226 this.webview.setStyle(options.styles);227 for(var key in options.extras) {228 this.webview[key] = options.extras[key];229 }230 } else {231 options.styles.left = '100%';232 if(from !== 'startAnimation') {233 options.styles.left = '0';234 plus.nativeUI.showWaiting();235 }236 this.webview = plus.webview.create(this.url, this.id, options.styles, options.extras);237 //appendè¿å»ï¼é¿å
è¿åæ¶éªå±238 plus.webview.currentWebview().append(this.webview);239 }240 this._initWebview();241 this.inited = true;242};243_proto._initWebview = function() {244 var options = this.options;245 if(!this.webview) {246 return;247 }248 this.webview.addEventListener('rendering', function() {249 setTimeout(function() {250 plus.nativeUI.closeWaiting();251 }, 500);252 });253 if(options.pullToRefresh && options.pullToRefresh.support && support.pullToRefresh()) {254 var callback = options.pullToRefresh.callback;255 this.webview.setPullToRefresh(options.pullToRefresh, function() {256 if(callback) { //å¦ææå®äºä¸æåè°257 callback(this.webview);258 } else { //ä¸æå·æ°åè°ï¼é»è®¤reloadå½å页é¢259 var self = this;260 var titleUpdate = function() {261 setTimeout(function() {262 self.webview.endPullToRefresh();263 }.bind(this), 1000);264 self.webview.removeEventListener('titleUpdate', titleUpdate);265 };266 this.webview.addEventListener('titleUpdate', titleUpdate);267 this.webview.reload();268 }269 }.bind(this));270 }...
text_Template.js
Source:text_Template.js
1var initTemplates = function() { //åå§å模æ¿2 getTemplate('default', 'test_template.html');3};4var templates = new Array;5var getTemplate = function(name, header, content) {6 var template = templates[name];7 if(!template) {8 //é¢å è½½å
±ç¨ç¶æ¨¡æ¿ï¼9 var headerWebview = mui.preload({10 url: header,11 id: name + "-main",12 styles: {13 popGesture: "hide",14 }15 });16 // //é¢å è½½å
±ç¨åwebview17 // var subWebview = mui.preload({18 // url: "",19 // id: name + "-sub",20 // styles: {21 // top: '45px',22 // bottom: '0px',23 // },24 // extras: {25 // mType: 'sub'26 // }27 // });28 // subWebview.addEventListener('titleUpdate', function() {29 // setTimeout(function() {30 // subWebview.show();31 // }, 50);32 // });33 // subWebview.hide();34 // headerWebview.append(subWebview);35 //iOSå¹³å°æ¯æ侧æ»å
³éï¼ç¶çªä½ä¾§æ»éèåï¼åæ¶éè¦éèåçªä½ï¼36 if(mui.os.ios) { //5+ç¶çªä½éèï¼åçªä½è¿å¯ä»¥çå°ï¼ä¸ç¬¦åé»è¾å§ï¼37 headerWebview.addEventListener('hide', function() {38 headerWebview.children().hide("none");39 });40 }41 templates[name] = template = {42 name: name,43 header: headerWebview,44 content: "",45 };46 }47 return template;48 49};5051function initShowContent(name, content) //å°æ¨¡æ¿ä¸å
容页ååå®æ52{53 var template = templates[name];54 console.log('template has '+template);55 if(!template) {56 var tempView = templates["default"];57 var template = {58 name:name,59 header:tempView.header60 }61 var subWebview = null;62 if(content) {63 subWebview = plus.webview.getWebviewById(content);64 }65 console.log((subWebview == null ? "isNull" : subWebview.getURL()))66 if(subWebview == null) {67 subWebview = mui.preload({68 url: content + ".html",69 id: content,70 styles: {71 top: '45px',72 bottom: '0px',73 },74 createNew: false75 });76 }77 var headerWebview = template.header;78 //var oldContentWebview = template.content;79 headerWebview.onloaded = headerLoading(subWebview);80 console.log("before remove,number of children is " + headerWebview.children().length)81 //headerWebview.remove(oldContentWebview);82 console.log("after remove, number of children is " + headerWebview.children().length)83 headerWebview.append(subWebview); //两个webviewå并84 //headerWebview.reload();85 template.content = subWebview;86 console.log("childrenview Url:" + headerWebview.children()[0].getURL())87 //oldContentWebview.hide();88 console.log("newview : " + subWebview.getURL())89 templates[name] = template;90 }91 return template;92};9394function headerLoading(subWebview) {95 subWebview.onloaded = subLoading(subWebview);96}9798function subLoading(subWebview) {99 console.log(subWebview.getURL())100 subWebview.show();101}102var hrefList = document.querySelectorAll(".mui-navigate-right")103var _len = hrefList.length;104for(var i = 0; i < _len; i++) {105 hrefList[i].addEventListener("tap", function(e) {106 //使ç¨ç¶å模æ¿æ¹æ¡æå¼ç页é¢107 var optid = e.currentTarget.getAttribute("data-id");108 //è·å¾å
±ç¨æ¨¡æ¿ç»109 //var template = getTemplate('myAttendance', 'myAttendance.html', 'myAttendance'); //è·å模æ¿å¯¹è±¡110 var template = initShowContent(optid, optid);111 //è·å¾å
±ç¨ç¶æ¨¡æ¿112 var headerWebview = template.header; //模æ¿å¤´113 //è·å¾å
±ç¨åwebview114 var contentWebview = template.content; //模æ¿å
容页115 var title = "æµè¯æ é¢" //è·å¾æ é¢å¤´çå
容116 //éç¥æ¨¡æ¿ä¿®æ¹æ é¢ï¼å¹¶æ¾ç¤ºéèå³ä¸è§å¾æ ï¼117 mui.fire(headerWebview, 'updateHeader', { //触åå
容页çäºä»¶118 title: title,119 target: optid + ".html",120 subWebId: optid121 });122 if(mui.os.ios || (mui.os.android && parseFloat(mui.os.version) < 4.4)) { //å¤ææºå123 var reload = true;124 // if(!template.loaded) { //å è½½å®æäºä»¶125 // if(contentWebview.getURL() != this.href) { //å¦æéèçviewä¸æ¯å½åçå页é¢è·¯å¾åå°é¡µé¢éæ°å è½½126 // contentWebview.loadURL(this.href);127 // } else {128 // reload = false;129 // }130 // } else {131 // reload = false;132 // }133 (!reload) && contentWebview.show(); //å¦æ为已å è½½ï¼åå¨æ¨¡æ¿é¡µéå®ç°å¦æ没æï¼åæ¾ç¤º134 headerWebview.show("pop-in", 150); //头é¨æ¾ç¤º135 }136 })
...
overlayWebView.js
Source:overlayWebView.js
1/*2 * Copyright 2012 Research In Motion Limited.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16var CHROME_HEIGHT = 0,17 webview,18 _webviewObj;19webview =20 {21 create: function (ready, configSettings) {22 _webviewObj = window.qnx.webplatform.createUIWebView(function () {23 _webviewObj.visible = true;24 _webviewObj.active = true;25 _webviewObj.zOrder = 2;26 _webviewObj.enableCrossSiteXHR = true;27 _webviewObj.setGeometry(0, 0, screen.width, screen.height);28 _webviewObj.addEventListener("DocumentLoadFinished", function () {29 _webviewObj.default.setDefaultFont();30 _webviewObj.visible = true;31 });32 _webviewObj.allowRpc = true;33 _webviewObj.backgroundColor = 0x00FFFFFF;34 _webviewObj.sensitivity = "SensitivityTest";35 _webviewObj.devicePixelRatio = 1;36 _webviewObj.allowQnxObject = true;37 if (ready && typeof ready === 'function') {38 ready();39 }40 window.qnx.webplatform.getController().dispatchEvent("overlayWebView.initialized", [_webviewObj]);41 });42 },43 destroy: function () {44 _webviewObj.destroy();45 },46 setURL: function (url) {47 _webviewObj.url = url;48 },49 setGeometry: function (x, y, width, height) {50 _webviewObj.setGeometry(x, y, width, height);51 },52 setSensitivity : function (sensitivity) {53 _webviewObj.sensitivity = sensitivity;54 },55 setApplicationOrientation: function (angle) {56 _webviewObj.setApplicationOrientation(angle);57 },58 notifyApplicationOrientationDone: function () {59 _webviewObj.notifyApplicationOrientationDone();60 },61 executeJavascript: function (js) {62 _webviewObj.executeJavaScript(js);63 },64 windowGroup: function () {65 return _webviewObj.windowGroup;66 },67 notifyContextMenuCancelled: function () {68 _webviewObj.notifyContextMenuCancelled();69 },70 bindAppWebViewToChildWebViewControls: function (appWebView) {71 if (_webviewObj && _webviewObj.childwebviewcontrols) {72 _webviewObj.childwebviewcontrols.subscribeTo(appWebView);73 }74 },75 renderContextMenuFor: function (targetWebView) {76 return _webviewObj.contextMenu.subscribeTo(targetWebView);77 },78 handleDialogFor: function (targetWebView) {79 return _webviewObj.dialog.subscribeTo(targetWebView);80 },81 showDialog: function (description, callback) {82 return _webviewObj.dialog.show(description, callback);83 },84 getWebViewObj: function (webview) {85 return _webviewObj;86 },87 addEventListener: function (eventName, callback) {88 _webviewObj.addEventListener(eventName, callback);89 },90 removeEventListener: function (eventName, callback) {91 _webviewObj.removeEventListener(eventName, callback);92 },93 showToast : function (message, options) {94 return _webviewObj.toast.show(message, options);95 },96 showInvocationList: function (request, title, success, error) {97 _webviewObj.invocationlist.show(request, title, success, error);98 }99};100webview.__defineGetter__('id', function () {101 if (_webviewObj) {102 return _webviewObj.id;103 }104});105webview.__defineGetter__('zOrder', function () {106 return _webviewObj.zOrder;107});108webview.__defineGetter__('contextMenu', function () {109 if (_webviewObj) {110 return _webviewObj.contextMenu;111 }112});...
WebFrame.spec.js
Source:WebFrame.spec.js
1import { mount } from '@vue/test-utils'2import WebFrame from '@/components/utils/WebFrame'3describe('WebFrame', () => {4 it('should be instantiated', () => {5 const wrapper = mount(WebFrame)6 expect(wrapper.isVisible()).toBeTrue()7 })8 it('should render an webview element', () => {9 const wrapper = mount(WebFrame)10 expect(wrapper.find('webview').exists()).toBeTrue()11 })12 it('should contain the enableremotemodule attribute', () => {13 const wrapper = mount(WebFrame)14 const webview = wrapper.find('webview')15 expect(webview.attributes('enableremotemodule')).toBe('false')16 })17 it('should contain the preload attribute', () => {18 const wrapper = mount(WebFrame)19 const webview = wrapper.find('webview')20 expect(webview.attributes('preload')).toBeTruthy()21 })22 it('should accept ark uri', () => {23 const wrapper = mount(WebFrame, {24 propsData: {25 src: 'ark:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'26 }27 })28 const webview = wrapper.find('webview')29 expect(webview.attributes('src')).toBe('ark:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')30 })31 it('should render http url', () => {32 const wrapper = mount(WebFrame, {33 propsData: {34 src: 'http://google.com'35 }36 })37 const webview = wrapper.find('webview')38 expect(webview.attributes('src')).toBe('http://google.com')39 })40 it('should not render file url', () => {41 const wrapper = mount(WebFrame, {42 propsData: {43 src: 'file://index.html'44 }45 })46 const webview = wrapper.find('webview')47 expect(webview.attributes('src')).toBe('about:blank')48 })49 it('should set custom size', () => {50 const wrapper = mount(WebFrame, {51 propsData: {52 width: 500,53 height: 50054 }55 })56 const webview = wrapper.find('webview')57 const { width, height } = webview.attributes()58 expect(width).toBe('500')59 expect(height).toBe('500')60 })...
Using AI Code Generation
1const { webkit } = require('playwright-internal');2(async () => {3 const browser = await webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { webkit } = require('playwright');10(async () => {11 const browser = await webkit.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();
Using AI Code Generation
1const { bebkit } = require('playwright-internal');2(async () => {3 const browser = await webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();
Using AI Code Generation
1const { { wkit } = require('playwright-internal');2(async () => {3 const browser = await webkit.launch();4 const pag await browser.newPagyuseragent.org/');5 await page.screenshot{ pahatsmyusera mntperg/png' });6 await browser.close();examp7})();8const { webkit require('playwright-interna Internal APIl');9(async () => {-internal10 const browser = await webkit.launch();11 const page = await browser.newPage();12 await browser.close()hatsmyuserantrg/13})();examp14cos{ wbki}=requre('playght-itrnal');15(async()=>{16 cnsbowsr= aiwebki.launc();17 cnst pag=aabrowsr.newPage();18a.screeshot({pah:'xample.pg});19waibrowe.clos();20})();21cons { wbkit} = require('');22(syn()=>{23csbowsr= aiwebki.launc();24 cnst pag=aabrowsr.newPage();25a.screeshot({pah:'xample.pg});26waibrowe.clos();27})();28cons { wbkit} = require('');29(syn()=>{30csbrowe =aiwebki.launc();31 constag=aabrowser.newPag();32ae.screnshot({ph:'exampl.pg});33awitbrwe.clos();34})();35cons { wbkit } =require('');36(async () => {37 onst browsr =awebt.lauch();38 cnst page=awitbrwe.newPag();39aage.sceenso({th: 'exmplpng' });40awit browsr.coe();
Using AI Code Generation
1cons ={ reqre('lywriht-irnal');2(ayc ()=>{3cosbrowe =ailaywight.wektlaunc();4cconxt =pagoer.newCoxt();5 cswebviw =aiage.weViw();playrihtdev/6 wit webviwclose();7awit browsr.coe();8})();9cos{ wbki}=requre('playght-itrnal');10(async()=>{11 cnsbowsr= aiwebki.launc();12 cnst pag=aabrowsr.newPage();13 witpge.screeshot({pah:'xample.pg});14waibrowe.clos();15})();16cons { wbkit} = require('');17(syn()=>{18 cntbrowsr=waitwebkit.lauch();19 cnspag= aibwsr.newPage();20wpage.sceho({pa:'exame.png' });21 abrowser.los();22})();23cons { wbkit} = require('');24(syn()=>{25 cntbrowsr=waitwebkit.lauch();26 cnspag= aibwsr.newPage();27wpage.sceho({ p: 'xame.png' });28 abrowser.los();29})();30con{webk } =requir('');31(async () => {32 onst browsr =awebt.lauch();33 cspag =aibwser.newPag();34 awaiscreenshot({pat: 'exmpl.png' });35 awit browser.coe();36})();
Using AI Code Generation
1c plywright =requir('');2(async () => {3 onst browsr =awplayight.webit.launch();4 contcotxt=awitbrowser.ewCntex();5 cont pag =aicontex.newPag();6 cnst weviw = awaitpage.webVew();7 wit webviwclose();8awit browsr.coe();9})();10 const browser = await webkit.launch();11 const page = await browser.newPage();12c await page.screenshot({ path: 'example.png' });13 await browser.close();14})();{hdless:fal }{/htwdless:fal }15 const webviewc=onst { webkiwaitFo}Event('webview');16 const webview = await w bviwaitFo.Evwit('webview');17 await webview.waitForLoadSrateL'domcontentloaded');18a Swaitewebview.click(it'dt=Get stortnd');19 await webviewtwaitForLoadState('domcontentloadedlded');20 eaw'ipywebview.click(wtrit=Get started');21 await webview.waitForLoadStgte('dohcontent-oadidn');22(async () => {23 const browser = await webkit.launch();24 const page = await browser.newPage();25 await page.screenshot({ path: 'example.png' });26 await browser.close();27})();28const { webkit } = require('playwright-internal');29(async () => {30 const browser = await webkit.launch();31 const page = await browser.newPage();32 await page.screenshot({ path: 'example.png' });33 await browser.close();34})();35const { webkit } = require('playwright-internal');36(async () => {37 const browser = await webkit.launch();38 const page = await browser.newPage();39 await page.screenshot({ path: 'example.png' });40 await browser.close();
Using AI Code Generation
1const webebkit } = require('playwright-internal');2(async () => {3 const browser = await webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { webkit } = require('playwright');10(async () => {11 const browser = await webkit.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();
Using AI Code Generation
1const { webkit } = require('playwright-internal');2(async () => {3 const browser = await webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();
Using AI Code Generation
1const webView = require('@playwright/test/webView');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const webview = await webView(page);8 await webview.waitForLoadState();9 await webview.waitForSelector('#foo');10 await webview.evaluate(() => {11 document.querySelector('#foo').click();12 });13 await browser.close();14})();15const { test, expect } = require('@playwright/test');16test('example test', async ({ page }) => {17 await page.waitForSelector('#foo');18 await page.evaluate(() => {19 document.querySelector('#foo').click();20 });21 const text = await page.innerText('#bar');22 expect(text).toBe('baz');23});24const { test, expect } = require('@playwright/test');25test.describe('example test suite', () => {26 test('example test', async ({ page }) => {27 await page.waitForSelector('#foo');ht-electron28require('playwright-electron').webView() await page.evaluate(() => {29 document.querySelector('#foo').cli30r quir,('playwright-i} =r rl').('@Viww()right/test');31t', async ({ page }) .wbVw32require('playwright-fioefxx).webView()33hocoigetu urye()hdo P-eetr34 quiwwq' aywrigelcr').Vw()
Using AI Code Generation
1require('playwright-firefox').webView()2const playwright = require('playwright');3const fs = require('fs');4(async () => {5 const browser = await playwright.chromium.launch();6 const page = await browser.newPage();7 const content = await page.webView().evaluate(() => document.documentElement.outerHTML);8 fs.writeFileSync('playwright.html', content);9 await browser.close();10})();
Using AI Code Generation
1 nst pag =awai brwr.nPag();2 const conteni = awath page of Play().evaluate(wr => do umdns.dacemantEl len.uterHTML);3 s.FiSynht.m', contnt);4 awai bsr.clos();5});6const playwright = require('playwright');7 const page = await browser.newPage();8 const content = await page.webView().evaluate(() => document.documentElement.outerHTML);9 fs.writeFileSync('playwright.html', content);10 await browser.close();11})();
Using AI Code Generation
1require('playwright-electron').webView()2const playwright = require('playwright');3const fs = require('fs');4(async () => {5 const browser = await playwright.chromium.launch();6 const page = await browser.newPage();7 const content = await page.webView().evaluate(() => document.documentElement.outerHTML);8 fs.writeFileSync('playwright.html', content);9 await browser.close();10})();11require('playwright-internal').webView()12require('playwright').webView()13require('playwright-chromium').webView()14require('playwright-firefox').webView()15require('playwright-webkit').webView()16require('playwright-electron').webView()17require('playwright-internal').webView()18require('playwright').webView()19require('playwright-chromium').webView()20require('playwright-firefox').webView()21require('playwright-webkit').webView()22require('playwright-electron').webView()23require('playwright-internal').webView()
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!