1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Shim that simulates a <webview> tag via Mutation Observers.
//
// The actual tag is implemented via the browser plugin. The internals of this
// are hidden via Shadow DOM.
var addTagWatcher = require('tagWatcher').addTagWatcher;
var eventBindings = require('event_bindings');
/** @type {Array.<string>} */
var WEB_VIEW_ATTRIBUTES = ['name', 'src', 'partition', 'autosize', 'minheight',
'minwidth', 'maxheight', 'maxwidth'];
var WEB_VIEW_EVENTS = {
'sizechanged': ['oldHeight', 'oldWidth', 'newHeight', 'newWidth'],
};
var createEvent = function(name) {
var eventOpts = {supportsListeners: true, supportsFilters: true};
return new eventBindings.Event(name, undefined, eventOpts);
};
var WEB_VIEW_EXT_EVENTS = {
'close': {
evt: createEvent('webview.onClose'),
fields: []
},
'consolemessage': {
evt: createEvent('webview.onConsoleMessage'),
fields: ['level', 'message', 'line', 'sourceId']
},
'contentload': {
evt: createEvent('webview.onContentLoad'),
fields: []
},
'exit': {
evt: createEvent('webview.onExit'),
fields: ['processId', 'reason']
},
'loadabort': {
evt: createEvent('webview.onLoadAbort'),
fields: ['url', 'isTopLevel', 'reason']
},
'loadcommit': {
customHandler: function(webview, event) {
webview.currentEntryIndex_ = event.currentEntryIndex;
webview.entryCount_ = event.entryCount;
webview.processId_ = event.processId;
if (event.isTopLevel) {
webview.browserPluginNode_.setAttribute('src', event.url);
}
},
evt: createEvent('webview.onLoadCommit'),
fields: ['url', 'isTopLevel']
},
'loadredirect': {
evt: createEvent('webview.onLoadRedirect'),
fields: ['isTopLevel', 'oldUrl', 'newUrl']
},
'loadstart': {
evt: createEvent('webview.onLoadStart'),
fields: ['url', 'isTopLevel']
},
'loadstop': {
evt: createEvent('webview.onLoadStop'),
fields: []
},
'responsive': {
evt: createEvent('webview.onResponsive'),
fields: ['processId']
},
'unresponsive': {
evt: createEvent('webview.onUnresponsive'),
fields: ['processId']
}
};
addTagWatcher('WEBVIEW', function(addedNode) { new WebView(addedNode); });
/** @type {number} */
WebView.prototype.entryCount_;
/** @type {number} */
WebView.prototype.currentEntryIndex_;
/** @type {number} */
WebView.prototype.processId_;
/**
* @constructor
*/
function WebView(webviewNode) {
this.webviewNode_ = webviewNode;
this.browserPluginNode_ = this.createBrowserPluginNode_();
var shadowRoot = this.webviewNode_.webkitCreateShadowRoot();
shadowRoot.appendChild(this.browserPluginNode_);
this.setupFocusPropagation_();
this.setupWebviewNodeMethods_();
this.setupWebviewNodeProperties_();
this.setupWebviewNodeAttributes_();
this.setupWebviewNodeEvents_();
// Experimental API
this.maybeSetupExperimentalAPI_();
}
/**
* @private
*/
WebView.prototype.createBrowserPluginNode_ = function() {
var browserPluginNode = document.createElement('object');
browserPluginNode.type = 'application/browser-plugin';
// The <object> node fills in the <webview> container.
browserPluginNode.style.width = '100%';
browserPluginNode.style.height = '100%';
$Array.forEach(WEB_VIEW_ATTRIBUTES, function(attributeName) {
// Only copy attributes that have been assigned values, rather than copying
// a series of undefined attributes to BrowserPlugin.
if (this.webviewNode_.hasAttribute(attributeName)) {
browserPluginNode.setAttribute(
attributeName, this.webviewNode_.getAttribute(attributeName));
} else if (this.webviewNode_[attributeName]){
// Reading property using has/getAttribute does not work on
// document.DOMContentLoaded event (but works on
// window.DOMContentLoaded event).
// So copy from property if copying from attribute fails.
browserPluginNode.setAttribute(
attributeName, this.webviewNode_[attributeName]);
}
}, this);
return browserPluginNode;
};
/**
* @private
*/
WebView.prototype.setupFocusPropagation_ = function() {
if (!this.webviewNode_.hasAttribute('tabIndex')) {
// <webview> needs a tabIndex in order to respond to keyboard focus.
// TODO(fsamuel): This introduces unexpected tab ordering. We need to find
// a way to take keyboard focus without messing with tab ordering.
// See http://crbug.com/231664.
this.webviewNode_.setAttribute('tabIndex', 0);
}
var self = this;
this.webviewNode_.addEventListener('focus', function(e) {
// Focus the BrowserPlugin when the <webview> takes focus.
self.browserPluginNode_.focus();
});
this.webviewNode_.addEventListener('blur', function(e) {
// Blur the BrowserPlugin when the <webview> loses focus.
self.browserPluginNode_.blur();
});
};
/**
* @private
*/
WebView.prototype.setupWebviewNodeMethods_ = function() {
// this.browserPluginNode_[apiMethod] are not necessarily defined immediately
// after the shadow object is appended to the shadow root.
var webviewNode = this.webviewNode_;
var browserPluginNode = this.browserPluginNode_;
var self = this;
webviewNode['canGoBack'] = function() {
return self.entryCount_ > 1 && self.currentEntryIndex_ > 0;
};
webviewNode['canGoForward'] = function() {
return self.currentEntryIndex_ >=0 &&
self.currentEntryIndex_ < (self.entryCount_ - 1);
};
webviewNode['back'] = function() {
webviewNode.go(-1);
};
webviewNode['forward'] = function() {
webviewNode.go(1);
};
webviewNode['getProcessId'] = function() {
return self.processId_;
};
webviewNode['go'] = function(relativeIndex) {
var instanceId = browserPluginNode.getGuestInstanceId();
if (!instanceId) {
return;
}
chrome.webview.go(instanceId, relativeIndex);
};
webviewNode['reload'] = function() {
var instanceId = browserPluginNode.getGuestInstanceId();
if (!instanceId) {
return;
}
chrome.webview.reload(instanceId);
};
webviewNode['stop'] = function() {
var instanceId = browserPluginNode.getGuestInstanceId();
if (!instanceId) {
return;
}
chrome.webview.stop(instanceId);
};
webviewNode['terminate'] = function() {
var instanceId = browserPluginNode.getGuestInstanceId();
if (!instanceId) {
return;
}
chrome.webview.terminate(instanceId);
};
this.setupExecuteCodeAPI_();
};
/**
* @private
*/
WebView.prototype.setupWebviewNodeProperties_ = function() {
var ERROR_MSG_CONTENTWINDOW_NOT_AVAILABLE = '<webview>: ' +
'contentWindow is not available at this time. It will become available ' +
'when the page has finished loading.';
var browserPluginNode = this.browserPluginNode_;
// Expose getters and setters for the attributes.
$Array.forEach(WEB_VIEW_ATTRIBUTES, function(attributeName) {
Object.defineProperty(this.webviewNode_, attributeName, {
get: function() {
return browserPluginNode[attributeName];
},
set: function(value) {
browserPluginNode[attributeName] = value;
},
enumerable: true
});
}, this);
// We cannot use {writable: true} property descriptor because we want dynamic
// getter value.
Object.defineProperty(this.webviewNode_, 'contentWindow', {
get: function() {
if (browserPluginNode.contentWindow)
return browserPluginNode.contentWindow;
console.error(ERROR_MSG_CONTENTWINDOW_NOT_AVAILABLE);
},
// No setter.
enumerable: true
});
};
/**
* @private
*/
WebView.prototype.setupWebviewNodeAttributes_ = function() {
this.setupWebviewNodeObservers_();
this.setupBrowserPluginNodeObservers_();
};
/**
* @private
*/
WebView.prototype.setupWebviewNodeObservers_ = function() {
// Map attribute modifications on the <webview> tag to property changes in
// the underlying <object> node.
var handleMutation = $Function.bind(function(mutation) {
this.handleWebviewAttributeMutation_(mutation);
}, this);
var observer = new MutationObserver(function(mutations) {
$Array.forEach(mutations, handleMutation);
});
observer.observe(
this.webviewNode_,
{attributes: true, attributeFilter: WEB_VIEW_ATTRIBUTES});
};
/**
* @private
*/
WebView.prototype.setupBrowserPluginNodeObservers_ = function() {
var handleMutation = $Function.bind(function(mutation) {
this.handleBrowserPluginAttributeMutation_(mutation);
}, this);
var objectObserver = new MutationObserver(function(mutations) {
$Array.forEach(mutations, handleMutation);
});
objectObserver.observe(
this.browserPluginNode_,
{attributes: true, attributeFilter: WEB_VIEW_ATTRIBUTES});
};
/**
* @private
*/
WebView.prototype.handleWebviewAttributeMutation_ = function(mutation) {
// This observer monitors mutations to attributes of the <webview> and
// updates the BrowserPlugin properties accordingly. In turn, updating
// a BrowserPlugin property will update the corresponding BrowserPlugin
// attribute, if necessary. See BrowserPlugin::UpdateDOMAttribute for more
// details.
this.browserPluginNode_[mutation.attributeName] =
this.webviewNode_.getAttribute(mutation.attributeName);
};
/**
* @private
*/
WebView.prototype.handleBrowserPluginAttributeMutation_ = function(mutation) {
// This observer monitors mutations to attributes of the BrowserPlugin and
// updates the <webview> attributes accordingly.
if (!this.browserPluginNode_.hasAttribute(mutation.attributeName)) {
// If an attribute is removed from the BrowserPlugin, then remove it
// from the <webview> as well.
this.webviewNode_.removeAttribute(mutation.attributeName);
} else {
// Update the <webview> attribute to match the BrowserPlugin attribute.
// Note: Calling setAttribute on <webview> will trigger its mutation
// observer which will then propagate that attribute to BrowserPlugin. In
// cases where we permit assigning a BrowserPlugin attribute the same value
// again (such as navigation when crashed), this could end up in an infinite
// loop. Thus, we avoid this loop by only updating the <webview> attribute
// if the BrowserPlugin attributes differs from it.
var oldValue = this.webviewNode_.getAttribute(mutation.attributeName);
var newValue = this.browserPluginNode_.getAttribute(mutation.attributeName);
if (newValue != oldValue) {
this.webviewNode_.setAttribute(mutation.attributeName, newValue);
}
}
};
/**
* @private
*/
WebView.prototype.setupWebviewNodeEvents_ = function() {
var self = this;
var onInstanceIdAllocated = function(e) {
var detail = e.detail ? JSON.parse(e.detail) : {};
self.instanceId_ = detail.windowId;
var params = {
'api': 'webview'
};
self.browserPluginNode_['-internal-attach'](params);
for (var eventName in WEB_VIEW_EXT_EVENTS) {
self.setupExtEvent_(eventName, WEB_VIEW_EXT_EVENTS[eventName]);
}
};
this.browserPluginNode_.addEventListener('-internal-instanceid-allocated',
onInstanceIdAllocated);
for (var eventName in WEB_VIEW_EVENTS) {
this.setupEvent_(eventName, WEB_VIEW_EVENTS[eventName]);
}
this.setupNewWindowEvent_();
this.setupPermissionEvent_();
};
/**
* @private
*/
WebView.prototype.setupExtEvent_ = function(eventName, eventInfo) {
var self = this;
var webviewNode = this.webviewNode_;
eventInfo.evt.addListener(function(event) {
var webviewEvent = new Event(eventName, {bubbles: true});
$Array.forEach(eventInfo.fields, function(field) {
webviewEvent[field] = event[field];
});
if (eventInfo.customHandler) {
eventInfo.customHandler(self, event);
}
webviewNode.dispatchEvent(webviewEvent);
}, {instanceId: self.instanceId_});
};
/**
* @private
*/
WebView.prototype.setupEvent_ = function(eventName, attribs) {
var webviewNode = this.webviewNode_;
var internalname = '-internal-' + eventName;
this.browserPluginNode_.addEventListener(internalname, function(e) {
var evt = new Event(eventName, { bubbles: true });
var detail = e.detail ? JSON.parse(e.detail) : {};
$Array.forEach(attribs, function(attribName) {
evt[attribName] = detail[attribName];
});
webviewNode.dispatchEvent(evt);
});
};
/**
* @private
*/
WebView.prototype.setupNewWindowEvent_ = function() {
var ERROR_MSG_NEWWINDOW_ACTION_ALREADY_TAKEN = '<webview>: ' +
'An action has already been taken for this "newwindow" event.';
var ERROR_MSG_NEWWINDOW_UNABLE_TO_ATTACH = '<webview>: ' +
'Unable to attach the new window to the provided webview.';
var ERROR_MSG_WEBVIEW_EXPECTED = '<webview> element expected.';
var showWarningMessage = function() {
var WARNING_MSG_NEWWINDOW_BLOCKED = '<webview>: A new window was blocked.';
console.warn(WARNING_MSG_NEWWINDOW_BLOCKED);
};
var NEW_WINDOW_EVENT_ATTRIBUTES = [
'initialHeight',
'initialWidth',
'targetUrl',
'windowOpenDisposition',
'name'
];
var self = this;
var node = this.webviewNode_;
var browserPluginNode = this.browserPluginNode_;
var onTrackedObjectGone = function(requestId, e) {
var detail = e.detail ? JSON.parse(e.detail) : {};
if (detail.id != requestId) {
return;
}
// If the request was pending then show a warning indiciating that a dialog
// was blocked.
if (browserPluginNode['-internal-setPermission'](requestId, false, '')) {
showWarningMessage();
}
};
browserPluginNode.addEventListener('-internal-newwindow', function(e) {
var evt = new Event('newwindow', { bubbles: true, cancelable: true });
var detail = e.detail ? JSON.parse(e.detail) : {};
$Array.forEach(NEW_WINDOW_EVENT_ATTRIBUTES, function(attribName) {
evt[attribName] = detail[attribName];
});
var requestId = detail.requestId;
var actionTaken = false;
var validateCall = function () {
if (actionTaken) {
throw new Error(ERROR_MSG_NEWWINDOW_ACTION_ALREADY_TAKEN);
}
actionTaken = true;
};
var window = {
attach: function(webview) {
validateCall();
if (!webview)
throw new Error(ERROR_MSG_WEBVIEW_EXPECTED);
// Attach happens asynchronously to give the tagWatcher an opportunity
// to pick up the new webview before attach operates on it, if it hasn't
// been attached to the DOM already.
// Note: Any subsequent errors cannot be exceptions because they happen
// asynchronously.
setTimeout(function() {
var attached =
browserPluginNode['-internal-attachWindowTo'](webview,
detail.windowId);
if (!attached) {
console.error(ERROR_MSG_NEWWINDOW_UNABLE_TO_ATTACH);
}
// If the object being passed into attach is not a valid <webview>
// then we will fail and it will be treated as if the new window
// was rejected. The permission API plumbing is used here to clean
// up the state created for the new window if attaching fails.
browserPluginNode['-internal-setPermission'](requestId, attached, '');
}, 0);
},
discard: function() {
validateCall();
browserPluginNode['-internal-setPermission'](requestId, false, '');
}
};
evt.window = window;
var defaultPrevented = !node.dispatchEvent(evt);
if (actionTaken) {
return;
}
if (defaultPrevented) {
// Make browser plugin track lifetime of |window|.
var onTrackedObjectGoneWithRequestId =
$Function.bind(onTrackedObjectGone, self, requestId);
browserPluginNode.addEventListener('-internal-trackedobjectgone',
onTrackedObjectGoneWithRequestId);
browserPluginNode['-internal-trackObjectLifetime'](window, requestId);
} else {
actionTaken = true;
// The default action is to discard the window.
browserPluginNode['-internal-setPermission'](requestId, false, '');
showWarningMessage();
}
});
};
/**
* @private
*/
WebView.prototype.setupExecuteCodeAPI_ = function() {
var ERROR_MSG_CANNOT_INJECT_SCRIPT = '<webview>: ' +
'Script cannot be injected into content until the page has loaded.';
var self = this;
var validateCall = function() {
if (!self.browserPluginNode_.getGuestInstanceId()) {
throw new Error(ERROR_MSG_CANNOT_INJECT_SCRIPT);
}
};
this.webviewNode_['executeScript'] = function(var_args) {
validateCall();
var args = $Array.concat([self.browserPluginNode_.getGuestInstanceId()],
$Array.slice(arguments));
$Function.apply(chrome.webview.executeScript, null, args);
}
this.webviewNode_['insertCSS'] = function(var_args) {
validateCall();
var args = $Array.concat([self.browserPluginNode_.getGuestInstanceId()],
$Array.slice(arguments));
$Function.apply(chrome.webview.insertCSS, null, args);
}
};
/**
* @param {!Object} detail The event details, originated from <object>.
* @private
*/
WebView.prototype.setupPermissionEvent_ = function() {
var ERROR_MSG_PERMISSION_ALREADY_DECIDED = '<webview>: ' +
'Permission has already been decided for this "permissionrequest" event.';
var showWarningMessage = function(permission) {
var WARNING_MSG_PERMISSION_DENIED = '<webview>: ' +
'The permission request for "%1" has been denied.';
console.warn(WARNING_MSG_PERMISSION_DENIED.replace('%1', permission));
};
var PERMISSION_TYPES = ['media', 'geolocation', 'pointerLock', 'download'];
var EXPOSED_PERMISSION_EVENT_ATTRIBS = [
'lastUnlockedBySelf',
'permission',
'requestMethod',
'url',
'userGesture'
];
var self = this;
var node = this.webviewNode_;
var browserPluginNode = this.browserPluginNode_;
var internalevent = '-internal-permissionrequest';
var onTrackedObjectGone = function(requestId, permission, e) {
var detail = e.detail ? JSON.parse(e.detail) : {};
if (detail.id != requestId)
return;
// If the request was pending then show a warning indiciating that the
// permission was denied.
if (browserPluginNode['-internal-setPermission'](requestId, false, '')) {
showWarningMessage(permission);
}
};
browserPluginNode.addEventListener(internalevent, function(e) {
var evt = new Event('permissionrequest', {bubbles: true, cancelable: true});
var detail = e.detail ? JSON.parse(e.detail) : {};
$Array.forEach(EXPOSED_PERMISSION_EVENT_ATTRIBS, function(attribName) {
if (detail[attribName] !== undefined)
evt[attribName] = detail[attribName];
});
var requestId = detail.requestId;
if (detail.requestId == undefined ||
PERMISSION_TYPES.indexOf(detail.permission) < 0) {
return;
}
// TODO(lazyboy): Also fill in evt.details (see webview specs).
// http://crbug.com/141197.
var decisionMade = false;
var validateCall = function() {
if (decisionMade) {
throw new Error(ERROR_MSG_PERMISSION_ALREADY_DECIDED);
}
decisionMade = true;
};
// Construct the event.request object.
var request = {
allow: function() {
validateCall();
browserPluginNode['-internal-setPermission'](requestId, true, '');
},
deny: function() {
validateCall();
browserPluginNode['-internal-setPermission'](requestId, false, '');
}
};
evt.request = request;
var defaultPrevented = !node.dispatchEvent(evt);
if (decisionMade) {
return;
}
if (defaultPrevented) {
// Make browser plugin track lifetime of |request|.
var onTrackedObjectGoneWithRequestId =
$Function.bind(
onTrackedObjectGone, self, requestId, detail.permission);
browserPluginNode.addEventListener('-internal-trackedobjectgone',
onTrackedObjectGoneWithRequestId);
browserPluginNode['-internal-trackObjectLifetime'](request, requestId);
} else {
decisionMade = true;
browserPluginNode['-internal-setPermission'](requestId, false, '');
showWarningMessage(detail.permission);
}
});
};
/**
* Implemented when the experimental API is available.
* @private
*/
WebView.prototype.maybeSetupExperimentalAPI_ = function() {};
exports.WebView = WebView;
|