Browse Source

Merge pull request #10711 from yuya-oc/did-attach-webview

Add did-attach-webview event
Cheng Zhao 7 years ago
parent
commit
4db34ff092

+ 10 - 0
docs/api/web-contents.md

@@ -581,6 +581,16 @@ that can't be set via `<webview>` attributes.
 **Note:** The specified `preload` script option will be appear as `preloadURL`
 (not `preload`) in the `webPreferences` object emitted with this event.
 
+#### Event: 'did-attach-webview'
+
+Returns:
+
+* `event` Event
+* `webContents` WebContents - The guest web contents that is used by the
+  `<webview>`.
+
+Emitted when a `<webview>` has been attached to this web contents.
+
 ### Instance Methods
 
 #### `contents.loadURL(url[, options])`

+ 2 - 1
lib/browser/guest-view-manager.js

@@ -76,7 +76,7 @@ const createGuest = function (embedder, params) {
   watchEmbedder(embedder)
 
   // Init guest web view after attached.
-  guest.on('did-attach', function () {
+  guest.on('did-attach', function (event) {
     params = this.attachParams
     delete this.attachParams
 
@@ -114,6 +114,7 @@ const createGuest = function (embedder, params) {
       this.loadURL(params.src, opts)
     }
     guest.allowPopups = params.allowpopups
+    embedder.emit('did-attach-webview', event, guest)
   })
 
   const sendToEmbedder = (channel, ...args) => {

+ 16 - 0
spec/fixtures/pages/webview-did-attach-event.html

@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+  </head>
+  <body>
+    <webview src="./a.html"/>
+    <script>
+      var {ipcRenderer} = require('electron')
+      var wv = document.querySelector('webview')
+      wv.addEventListener('dom-ready', () => {
+        ipcRenderer.send('webview-dom-ready', wv.getWebContents().id)
+      })
+    </script>
+  </body>
+</html>

+ 15 - 0
spec/webview-spec.js

@@ -1183,6 +1183,21 @@ describe('<webview> tag', function () {
     })
   })
 
+  describe('did-attach-webview event', () => {
+    it('is emitted when a webview has been attached', (done) => {
+      w = new BrowserWindow({
+        show: false
+      })
+      w.webContents.on('did-attach-webview', (event, webContents) => {
+        ipcMain.once('webview-dom-ready', (event, id) => {
+          assert.equal(webContents.id, id)
+          done()
+        })
+      })
+      w.loadURL('file://' + fixtures + '/pages/webview-did-attach-event.html')
+    })
+  })
+
   it('loads devtools extensions registered on the parent window', function (done) {
     w = new BrowserWindow({
       show: false