Browse Source

feat: introduce LocationProxy for BrowserWindowProxy

Anrock 6 years ago
parent
commit
e80e3a53e9
1 changed files with 48 additions and 10 deletions
  1. 48 10
      lib/renderer/window-setup.js

+ 48 - 10
lib/renderer/window-setup.js

@@ -23,7 +23,7 @@
 // - document.hidden
 // - document.visibilityState
 
-const { defineProperty } = Object
+const { defineProperty, defineProperties } = Object
 
 // Helper function to resolve relative url.
 const a = window.top.document.createElement('a')
@@ -54,19 +54,57 @@ const removeProxy = (guestId) => {
   delete windowProxies[guestId]
 }
 
-function BrowserWindowProxy (ipcRenderer, guestId) {
-  this.closed = false
+function LocationProxy (ipcRenderer, guestId) {
+  const getGuestURL = function () {
+    const urlString = ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD_SYNC', guestId, 'getURL')
+    try {
+      return new URL(urlString)
+    } catch (e) {
+      console.error('LocationProxy: failed to parse string', urlString, e)
+    }
 
-  defineProperty(this, 'location', {
-    get: function () {
-      return ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD_SYNC', guestId, 'getURL')
-    },
-    set: function (url) {
-      url = resolveURL(url)
-      return ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD_SYNC', guestId, 'loadURL', url)
+    return null
+  }
+
+  const propertyProxyFor = function (property) {
+    return {
+      get: function () {
+        const guestURL = getGuestURL()
+        return guestURL ? guestURL[property] : ''
+      },
+      set: function (newVal) {
+        const guestURL = getGuestURL()
+        if (guestURL) {
+          guestURL[property] = newVal
+          return ipcRenderer.sendSync(
+            'ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD_SYNC',
+            guestId, 'loadURL', guestURL.toString())
+        }
+      }
     }
+  }
+
+  defineProperties(this, {
+    hash: propertyProxyFor('hash'),
+    href: propertyProxyFor('href'),
+    host: propertyProxyFor('host'),
+    hostname: propertyProxyFor('hostname'),
+    origin: propertyProxyFor('origin'),
+    pathname: propertyProxyFor('pathname'),
+    port: propertyProxyFor('port'),
+    protocol: propertyProxyFor('protocol'),
+    search: propertyProxyFor('search')
   })
 
+  this.toString = function () {
+    return this.href
+  }
+}
+
+function BrowserWindowProxy (ipcRenderer, guestId) {
+  this.closed = false
+  this.location = new LocationProxy(ipcRenderer, guestId)
+
   ipcRenderer.once(`ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_${guestId}`, () => {
     removeProxy(guestId)
     this.closed = true