fix: use OOPIF for webview tag (#13869)

* fix: use OOIF for webview tag

* fix: do not call GetNativeView for webview

* fix: OOIPF webview's WebContents is managed by embedder frame

* fix: guest view can not be focused

* fix: clear zoom controller when guest is destroyed

* fix: implement the webview resize event

The webview is no longer a browser plugin with the resize event, use
ResizeObserver instead.

* test: disable failed tests due to OOPIF webview

* fix: embedder can be destroyed earlier than guest

This happens when embedder is manually destroyed.

* fix: don't double attach

* fix: recreate iframe when webview is reattached

* fix: resize event may happen very early

* test: some tests are working after OOPIF webview

* chore: remove unused browser plugin webview code

* fix: get embedder via closure

When the "destroyed" event is emitted, the entry in guestInstances would be
cleared.

* chore: rename browserPluginNode to internalElement

* test: make the visibilityState test more robust

* chore: guestinstance can not work with OOPIF webview

* fix: element could be detached before got response from browser
This commit is contained in:
Cheng Zhao 2018-08-16 15:57:40 -07:00 committed by Charles Kerr
parent 48407c5b93
commit dd5b8769be
28 changed files with 268 additions and 1008 deletions

View file

@ -61,7 +61,6 @@ const dispatchEvent = function (webView, eventName, eventKey, ...args) {
module.exports = {
registerEvents: function (webView, viewInstanceId) {
ipcRenderer.on(`ELECTRON_GUEST_VIEW_INTERNAL_DESTROY_GUEST-${viewInstanceId}`, function () {
webFrame.detachGuest(webView.internalInstanceId)
webView.guestInstanceId = undefined
webView.reset()
const domEvent = new Event('destroyed')
@ -78,22 +77,11 @@ module.exports = {
domEvent.args = args
webView.dispatchEvent(domEvent)
})
ipcRenderer.on(`ELECTRON_GUEST_VIEW_INTERNAL_SIZE_CHANGED-${viewInstanceId}`, function (event, ...args) {
const domEvent = new Event('size-changed')
const props = ['oldWidth', 'oldHeight', 'newWidth', 'newHeight']
for (let i = 0; i < props.length; i++) {
const prop = props[i]
domEvent[prop] = args[i]
}
webView.onSizeChanged(domEvent)
})
},
deregisterEvents: function (viewInstanceId) {
ipcRenderer.removeAllListeners(`ELECTRON_GUEST_VIEW_INTERNAL_DESTROY_GUEST-${viewInstanceId}`)
ipcRenderer.removeAllListeners(`ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-${viewInstanceId}`)
ipcRenderer.removeAllListeners(`ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE-${viewInstanceId}`)
ipcRenderer.removeAllListeners(`ELECTRON_GUEST_VIEW_INTERNAL_SIZE_CHANGED-${viewInstanceId}`)
},
createGuest: function (params, callback) {
requestId++
@ -103,14 +91,11 @@ module.exports = {
createGuestSync: function (params) {
return ipcRenderer.sendSync('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST_SYNC', params)
},
attachGuest: function (elementInstanceId, guestInstanceId, params) {
ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', elementInstanceId, guestInstanceId, params)
webFrame.attachGuest(elementInstanceId)
},
destroyGuest: function (guestInstanceId) {
ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_DESTROY_GUEST', guestInstanceId)
},
setSize: function (guestInstanceId, params) {
ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params)
attachGuest: function (elementInstanceId, guestInstanceId, params, contentWindow) {
const embedderFrameId = webFrame.getWebFrameId(contentWindow)
if (embedderFrameId < 0) { // this error should not happen.
throw new Error('Invalid embedder frame')
}
ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', embedderFrameId, elementInstanceId, guestInstanceId, params)
}
}

View file

@ -1,7 +1,6 @@
'use strict'
const WebViewImpl = require('./web-view')
const guestViewInternal = require('./guest-view-internal')
const webViewConstants = require('./web-view-constants')
const {remote} = require('electron')
@ -74,39 +73,6 @@ class BooleanAttribute extends WebViewAttribute {
}
}
// Attribute used to define the demension limits of autosizing.
class AutosizeDimensionAttribute extends WebViewAttribute {
getValue () {
return parseInt(this.webViewImpl.webviewNode.getAttribute(this.name)) || 0
}
handleMutation () {
if (!this.webViewImpl.guestInstanceId) {
return
}
guestViewInternal.setSize(this.webViewImpl.guestInstanceId, {
enableAutoSize: this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE].getValue(),
min: {
width: parseInt(this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() || 0),
height: parseInt(this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_MINHEIGHT].getValue() || 0)
},
max: {
width: parseInt(this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() || 0),
height: parseInt(this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() || 0)
}
})
}
}
// Attribute that specifies whether the webview should be autosized.
class AutosizeAttribute extends BooleanAttribute {
constructor (webViewImpl) {
super(webViewConstants.ATTRIBUTE_AUTOSIZE, webViewImpl)
}
}
AutosizeAttribute.prototype.handleMutation = AutosizeDimensionAttribute.prototype.handleMutation
// Attribute representing the state of the storage partition.
class PartitionAttribute extends WebViewAttribute {
constructor (webViewImpl) {
@ -130,43 +96,6 @@ class PartitionAttribute extends WebViewAttribute {
}
}
// An attribute that controls the guest instance this webview is connected to
class GuestInstanceAttribute extends WebViewAttribute {
constructor (webViewImpl) {
super(webViewConstants.ATTRIBUTE_GUESTINSTANCE, webViewImpl)
}
// Retrieves and returns the attribute's value.
getValue () {
if (this.webViewImpl.webviewNode.hasAttribute(this.name)) {
return parseInt(this.webViewImpl.webviewNode.getAttribute(this.name))
}
}
// Sets the attribute's value.
setValue (value) {
if (!value) {
this.webViewImpl.webviewNode.removeAttribute(this.name)
} else if (!isNaN(value)) {
this.webViewImpl.webviewNode.setAttribute(this.name, value)
}
}
handleMutation (oldValue, newValue) {
if (!newValue) {
this.webViewImpl.reset()
return
}
const intVal = parseInt(newValue)
if (!isNaN(newValue) && remote.getGuestWebContents(intVal)) {
this.webViewImpl.attachGuestInstance(intVal)
} else {
this.setValueIgnoreMutation(oldValue)
}
}
}
// Attribute that handles the location and navigation of the webview.
class SrcAttribute extends WebViewAttribute {
constructor (webViewImpl) {
@ -314,7 +243,6 @@ class WebPreferencesAttribute extends WebViewAttribute {
// Sets up all of the webview attributes.
WebViewImpl.prototype.setupWebViewAttributes = function () {
this.attributes = {}
this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE] = new AutosizeAttribute(this)
this.attributes[webViewConstants.ATTRIBUTE_PARTITION] = new PartitionAttribute(this)
this.attributes[webViewConstants.ATTRIBUTE_SRC] = new SrcAttribute(this)
this.attributes[webViewConstants.ATTRIBUTE_HTTPREFERRER] = new HttpReferrerAttribute(this)
@ -326,12 +254,5 @@ WebViewImpl.prototype.setupWebViewAttributes = function () {
this.attributes[webViewConstants.ATTRIBUTE_PRELOAD] = new PreloadAttribute(this)
this.attributes[webViewConstants.ATTRIBUTE_BLINKFEATURES] = new BlinkFeaturesAttribute(this)
this.attributes[webViewConstants.ATTRIBUTE_DISABLEBLINKFEATURES] = new DisableBlinkFeaturesAttribute(this)
this.attributes[webViewConstants.ATTRIBUTE_GUESTINSTANCE] = new GuestInstanceAttribute(this)
this.attributes[webViewConstants.ATTRIBUTE_DISABLEGUESTRESIZE] = new BooleanAttribute(webViewConstants.ATTRIBUTE_DISABLEGUESTRESIZE, this)
this.attributes[webViewConstants.ATTRIBUTE_WEBPREFERENCES] = new WebPreferencesAttribute(this)
const autosizeAttributes = [webViewConstants.ATTRIBUTE_MAXHEIGHT, webViewConstants.ATTRIBUTE_MAXWIDTH, webViewConstants.ATTRIBUTE_MINHEIGHT, webViewConstants.ATTRIBUTE_MINWIDTH]
autosizeAttributes.forEach((attribute) => {
this.attributes[attribute] = new AutosizeDimensionAttribute(attribute, this)
})
}

View file

@ -1,10 +1,5 @@
module.exports = {
// Attributes.
ATTRIBUTE_AUTOSIZE: 'autosize',
ATTRIBUTE_MAXHEIGHT: 'maxheight',
ATTRIBUTE_MAXWIDTH: 'maxwidth',
ATTRIBUTE_MINHEIGHT: 'minheight',
ATTRIBUTE_MINWIDTH: 'minwidth',
ATTRIBUTE_NAME: 'name',
ATTRIBUTE_PARTITION: 'partition',
ATTRIBUTE_SRC: 'src',
@ -17,8 +12,6 @@ module.exports = {
ATTRIBUTE_USERAGENT: 'useragent',
ATTRIBUTE_BLINKFEATURES: 'blinkfeatures',
ATTRIBUTE_DISABLEBLINKFEATURES: 'disableblinkfeatures',
ATTRIBUTE_GUESTINSTANCE: 'guestinstance',
ATTRIBUTE_DISABLEGUESTRESIZE: 'disableguestresize',
ATTRIBUTE_WEBPREFERENCES: 'webpreferences',
// Internal attribute.

View file

@ -6,8 +6,6 @@ const v8Util = process.atomBinding('v8_util')
const guestViewInternal = require('./guest-view-internal')
const webViewConstants = require('./web-view-constants')
const hasProp = {}.hasOwnProperty
// An unique ID that can represent current context.
const contextId = v8Util.getHiddenValue(global, 'contextId')
@ -23,27 +21,27 @@ class WebViewImpl {
constructor (webviewNode) {
this.webviewNode = webviewNode
v8Util.setHiddenValue(this.webviewNode, 'internal', this)
this.attached = false
this.elementAttached = false
this.beforeFirstNavigation = true
// on* Event handlers.
this.on = {}
this.browserPluginNode = this.createBrowserPluginNode()
this.internalElement = this.createInternalElement()
const shadowRoot = this.webviewNode.attachShadow({mode: 'open'})
shadowRoot.innerHTML = '<!DOCTYPE html><style type="text/css">:host { display: flex; }</style>'
this.setupWebViewAttributes()
this.setupFocusPropagation()
this.viewInstanceId = getNextId()
shadowRoot.appendChild(this.browserPluginNode)
shadowRoot.appendChild(this.internalElement)
}
createBrowserPluginNode () {
// We create BrowserPlugin as a custom element in order to observe changes
// to attributes synchronously.
const browserPluginNode = new WebViewImpl.BrowserPlugin()
v8Util.setHiddenValue(browserPluginNode, 'internal', this)
return browserPluginNode
createInternalElement () {
const iframeElement = document.createElement('iframe')
iframeElement.style.width = '100%'
iframeElement.style.height = '100%'
iframeElement.style.border = '0'
v8Util.setHiddenValue(iframeElement, 'internal', this)
return iframeElement
}
// Resets some state upon reattaching <webview> element to the DOM.
@ -55,7 +53,6 @@ class WebViewImpl {
// heard back from createGuest yet. We will not reset the flag in this case so
// that we don't end up allocating a second guest.
if (this.guestInstanceId) {
guestViewInternal.destroyGuest(this.guestInstanceId)
this.guestInstanceId = void 0
}
@ -63,9 +60,12 @@ class WebViewImpl {
this.beforeFirstNavigation = true
this.attributes[webViewConstants.ATTRIBUTE_PARTITION].validPartitionId = true
// Set guestinstance last since this can trigger the attachedCallback to fire
// when moving the webview using element.replaceChild
this.attributes[webViewConstants.ATTRIBUTE_GUESTINSTANCE].setValueIgnoreMutation(undefined)
// Since attachment swaps a local frame for a remote frame, we need our
// internal iframe element to be local again before we can reattach.
const newFrame = this.createInternalElement()
const oldFrame = this.internalElement
this.internalElement = newFrame
oldFrame.parentNode.replaceChild(newFrame, oldFrame)
}
// Sets the <webview>.request property.
@ -87,12 +87,12 @@ class WebViewImpl {
// Focus the BrowserPlugin when the <webview> takes focus.
this.webviewNode.addEventListener('focus', () => {
this.browserPluginNode.focus()
this.internalElement.focus()
})
// Blur the BrowserPlugin when the <webview> loses focus.
this.webviewNode.addEventListener('blur', () => {
this.browserPluginNode.blur()
this.internalElement.blur()
})
}
@ -110,62 +110,11 @@ class WebViewImpl {
this.attributes[attributeName].handleMutation(oldValue, newValue)
}
handleBrowserPluginAttributeMutation (attributeName, oldValue, newValue) {
if (attributeName === webViewConstants.ATTRIBUTE_INTERNALINSTANCEID && !oldValue && !!newValue) {
this.browserPluginNode.removeAttribute(webViewConstants.ATTRIBUTE_INTERNALINSTANCEID)
this.internalInstanceId = parseInt(newValue)
// Track when the element resizes using the element resize callback.
webFrame.registerElementResizeCallback(this.internalInstanceId, this.onElementResize.bind(this))
if (this.guestInstanceId) {
guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams())
}
}
}
onSizeChanged (webViewEvent) {
const {newHeight, newWidth} = webViewEvent
const node = this.webviewNode
const width = node.offsetWidth
// Check the current bounds to make sure we do not resize <webview>
// outside of current constraints.
const maxWidth = this.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() | width
const maxHeight = this.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() | width
let minWidth = this.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() | width
let minHeight = this.attributes[webViewConstants.ATTRIBUTE_MINHEIGHT].getValue() | width
minWidth = Math.min(minWidth, maxWidth)
minHeight = Math.min(minHeight, maxHeight)
if (!this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE].getValue() || (newWidth >= minWidth && newWidth <= maxWidth && newHeight >= minHeight && newHeight <= maxHeight)) {
node.style.width = `${newWidth}px`
node.style.height = `${newHeight}px`
// Only fire the DOM event if the size of the <webview> has actually
// changed.
this.dispatchEvent(webViewEvent)
}
}
onElementResize (newSize) {
// Dispatch the 'resize' event.
const resizeEvent = new Event('resize', {
bubbles: true
})
// Using client size values, because when a webview is transformed `newSize`
// is incorrect
newSize.width = this.webviewNode.clientWidth
newSize.height = this.webviewNode.clientHeight
resizeEvent.newWidth = newSize.width
resizeEvent.newHeight = newSize.height
onElementResize () {
const resizeEvent = new Event('resize', { bubbles: true })
resizeEvent.newWidth = this.webviewNode.clientWidth
resizeEvent.newHeight = this.webviewNode.clientHeight
this.dispatchEvent(resizeEvent)
if (this.guestInstanceId &&
!this.attributes[webViewConstants.ATTRIBUTE_DISABLEGUESTRESIZE].getValue()) {
guestViewInternal.setSize(this.guestInstanceId, {
normal: newSize
})
}
}
createGuest () {
@ -175,6 +124,7 @@ class WebViewImpl {
}
createGuestSync () {
this.beforeFirstNavigation = false
this.attachGuestInstance(guestViewInternal.createGuestSync(this.buildParams()))
}
@ -225,64 +175,30 @@ class WebViewImpl {
userAgentOverride: this.userAgentOverride
}
for (const attributeName in this.attributes) {
if (hasProp.call(this.attributes, attributeName)) {
if (this.attributes.hasOwnProperty(attributeName)) {
params[attributeName] = this.attributes[attributeName].getValue()
}
}
// When the WebView is not participating in layout (display:none)
// then getBoundingClientRect() would report a width and height of 0.
// However, in the case where the WebView has a fixed size we can
// use that value to initially size the guest so as to avoid a relayout of
// the on display:block.
const css = window.getComputedStyle(this.webviewNode, null)
const elementRect = this.webviewNode.getBoundingClientRect()
params.elementWidth = parseInt(elementRect.width) || parseInt(css.getPropertyValue('width'))
params.elementHeight = parseInt(elementRect.height) || parseInt(css.getPropertyValue('height'))
return params
}
attachGuestInstance (guestInstanceId) {
if (!this.elementAttached) {
// The element could be detached before we got response from browser.
return
}
this.internalInstanceId = getNextId()
this.guestInstanceId = guestInstanceId
this.attributes[webViewConstants.ATTRIBUTE_GUESTINSTANCE].setValueIgnoreMutation(guestInstanceId)
this.webContents = remote.getGuestWebContents(this.guestInstanceId)
if (!this.internalInstanceId) {
return true
}
return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams())
guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams(), this.internalElement.contentWindow)
// ResizeObserver is a browser global not recognized by "standard".
/* globals ResizeObserver */
// TODO(zcbenz): Should we deprecate the "resize" event? Wait, it is not
// even documented.
this.resizeObserver = new ResizeObserver(this.onElementResize.bind(this)).observe(this.internalElement)
}
}
// Registers browser plugin <object> custom element.
const registerBrowserPluginElement = function () {
const proto = Object.create(HTMLObjectElement.prototype)
proto.createdCallback = function () {
this.setAttribute('type', 'application/browser-plugin')
this.setAttribute('id', `browser-plugin-${getNextId()}`)
// The <object> node fills in the <webview> container.
this.style.flex = '1 1 auto'
}
proto.attributeChangedCallback = function (name, oldValue, newValue) {
const internal = v8Util.getHiddenValue(this, 'internal')
if (internal) {
internal.handleBrowserPluginAttributeMutation(name, oldValue, newValue)
}
}
proto.attachedCallback = function () {
// Load the plugin immediately.
return this.nonExistentAttribute
}
WebViewImpl.BrowserPlugin = webFrame.registerEmbedderCustomElement('browserplugin', {
'extends': 'object',
prototype: proto
})
delete proto.createdCallback
delete proto.attachedCallback
delete proto.detachedCallback
delete proto.attributeChangedCallback
}
// Registers <webview> custom element.
const registerWebViewElement = function () {
const proto = Object.create(HTMLObjectElement.prototype)
@ -313,12 +229,7 @@ const registerWebViewElement = function () {
if (!internal.elementAttached) {
guestViewInternal.registerEvents(internal, internal.viewInstanceId)
internal.elementAttached = true
const instance = internal.attributes[webViewConstants.ATTRIBUTE_GUESTINSTANCE].getValue()
if (instance) {
internal.attachGuestInstance(instance)
} else {
internal.attributes[webViewConstants.ATTRIBUTE_SRC].parse()
}
internal.attributes[webViewConstants.ATTRIBUTE_SRC].parse()
}
}
@ -450,7 +361,6 @@ const listener = function (event) {
if (document.readyState === 'loading') {
return
}
registerBrowserPluginElement()
registerWebViewElement()
window.removeEventListener(event.type, listener, useCapture)
}