在具有 Electron 的同一个 BrowserWindow 中有两个隔离的(就历史/cookies/本地存储而言)B

Having two isolated (in terms of history/cookies/localstorage) BrowserViews in the same BrowserWindow with Electron(在具有 Electron 的同一个 BrowserWindow 中有两个隔离的(就历史/cookies/本地存储而言)BrowserViews) - IT屋-程序员软件开发技术分
本文介绍了在具有 Electron 的同一个 BrowserWindow 中有两个隔离的(就历史/cookies/本地存储而言)BrowserViews的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

假设我在同一个 BrowserWindow 中有两个 BrowserView 和一个 UI 按钮,允许用户在显示 bv1 之间切换bv2(就像 Firefox、Chrome 等浏览器中的标签"系统,允许您在不同页面之间切换):

Let's say I have two BrowserView in the same BrowserWindow and an UI button allowing the user to switch between showing bv1 or bv2 (like the "tab" system in browsers like Firefox, Chrome, that allows you to switch between the different pages):

browserWindow = new BrowserWindow({ width: 1200, height: 600 });

let bv1 = new BrowserView({ webPreferences: { nodeIntegration: false }});
bv1.setBounds({ x: 0, y: 0, width: 1200, height: 600 });
bv1.webContents.loadURL('https://www.twitter.com');

let bv2 = new BrowserView({ webPreferences: { nodeIntegration: false }});
bv2.setBounds({ x: 0, y: 0, width: 1200, height: 600 });
bv2.webContents.loadURL('https://www.twitter.com');

browserWindow.setBrowserView(bv1);

当按下按钮(如浏览器中的标签")时:

and when a button (like a "tab" in a browser) is pressed:

browserWindow.setBrowserView(bv2);

我注意到这两个BrowserView:

  • 共享相同的 cookie/localStorage(我不想要!),即如果第一个连接到一个帐户,第二个也将连接到同一个帐户

  • share the same cookies/localStorage (which I don't want!), i.e. if the first is connected to an account, the second will be connected as well to the same account

重启 Electron 应用后保留历史记录和 cookie(这很好,确实需要!)

keep history and cookies after restart of the Electron app (this is good and wanted indeed!)

问题:如何让两个 BrowserView 在 cookie/localStorage/history 方面完全隔离(因此 bv1 可以连接到一个 Twitter 帐户并 bv2 连接到另一个)?

Question: how to have the two BrowserView totally isolated in terms of cookies/localStorage/history (and thus bv1 could be connected to one Twitter account and bv2 to another one)?

推荐答案

所以,我设法以一种非常、非常、迂回的方式完成了这项工作.有效地劫持您自己的会话,在应用程序关闭/打开时保存和加载它.下面的代码带有一些注释,前面有一些有用的链接.这在以开发人员身份运行以及与构建应用程序一起运行时有效.

So, I managed to get this working but in a very, very, roundabout way. Effectively session hijacking your own session, saving and loading it on app close/open. Code below with some comments, prefaced with some useful links. This worked when running as dev, and when running with a build application.

您可能需要在此处查看像这样在本地存储 cookie 可能存在的安全问题.

You may need to look into possible security issues here with storing cookies locally like this.

我在这个答案中唯一没有解决的是:

The only thing I have not tackled in this answer is:

在 Electron 应用重启后保留历史记录

keep history ... after restart of the Electron app

<小时>

  • Electron-Json-Storage 包 - 我们使用它来存储/检索饼干.默认存储位置是 C:Users\%user%AppDataRoaming\%appname%storage.
  • 电子 Cookie 文档
  • Electron Session 文档 - 特别是 session.fromPartition 文档.

    • Electron-Json-Storage Package - We use this to store/retrieve cookies. The default location for storage is C:Users\%user%AppDataRoaming\%appname%storage.
    • Electron Cookies documentation
    • Electron Session documentation - Notably the session.fromPartition docs.
    • const { app, BrowserWindow, BrowserView, globalShortcut, session } = require('electron');
      const eJSONStorage = require('electron-json-storage');
      
      // Our two different sesions, views, and base URL for our 'tabs'.
      let bv1Session, bv2Session = session;
      let bv1, bv2 = BrowserView;
      const appTabUrl = 'https://www.twitter.com';
      
      app.on('ready', () => {
        const width = 1200; const height = 600;
        let b1Active = true;
      
        // Our browser window
        browserWindow = new BrowserWindow({
          width: width,
          height: height,
        });
      
        // Our first browser window with it's own session instance.
        bv1Session = session.fromPartition('persist:bv1Session', { cache: true });
        bv1 = createBrowserView(appTabUrl, bv1Session, width, height);
        loadCookieState('view1Cookies', bv1Session);
      
        // Our second browser window with it's own session instance.
        bv2Session = session.fromPartition('persist:bv2Session', { cache: true });
        bv2 = createBrowserView(appTabUrl, bv2Session, width, height);
        loadCookieState('view2Cookies', bv2Session);
      
        // Our initial setting of the browserview
        browserWindow.setBrowserView(bv1);
      
        // Our shortcut listener and basic switch mechanic
        // Set to [CTRL + /] for windows or [CMD + /] for OSX
        globalShortcut.register('CommandOrControl+/', () => {
          b1Active ? browserWindow.setBrowserView(bv2) : browserWindow.setBrowserView(bv1);
          b1Active = !b1Active
        });
      });
      
      // When the app closes, exit gracefully.
      // Unregister keypress listener, save cookie states, exit the app.
      app.on('window-all-closed', () => {
        globalShortcut.unregisterAll();
        saveCookieState('view1Cookies', bv1Session);
        saveCookieState('view2Cookies', bv2Session);
        app.quit();
      })
      
      // Helper method to generate a browser view.
      function createBrowserView(url, session, width, height) {
        let browserView = new BrowserView({
          webPreferences: {
            nodeIntegration: false,
            nodeIntegrationInWorker: false,
            session: session
          }
        });
        browserView.setBounds({ x: 0, y: 0, width: width, height: height });
        browserView.webContents.loadURL(url);
        return browserView;
      }
      
      // Method that takes a session name, and our current session to save its state.
      function saveCookieState(sessionName, currentSession) {
        currentSession.cookies.get({}, (_, cookies) => {
          cookies.forEach(cookie => {
            // URL is a required paramater, take it from the domain with a little parsing.
            // Twitter always uses HTTPS otherwise, we would need to check for http vs https too.
            const cDomain = !cookie.domain.startsWith('.') ? `.${cookie.domain}` : cookie.domain;
            cookie.url = `https://www${cDomain}`
          });
          // Save the set of cookies against the session name.
          eJSONStorage.set(sessionName, cookies, err => {
            if (err) {
              throw err;
            }
          });
        });
      }
      
      // Method that loads a session based on its name, into a session created by us.
      function loadCookieState(sessionName, currentSession) {
        eJSONStorage.get(sessionName, (error, cookieData) => {
          // Check for empty object returned, this means no saved sessions.
          if (Object.entries(cookieData).length === 0) {
            return;
          }
          if (error) {
            throw error;
          }
          // If we have saved sessions and no errors, load the sessions.
          cookieData.forEach(cookie => currentSession.cookies.set(cookie, error => {
            if (error) console.error(error);
          }));
        });
      }
      

      这篇关于在具有 Electron 的同一个 BrowserWindow 中有两个隔离的(就历史/cookies/本地存储而言)BrowserViews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

      本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Google apps script get range of bytes from binary file(谷歌应用程序脚本从二进制文件中获取字节范围)
Sending Multiple attachments with Google Script from Google Drive(使用 Google 脚本从 Google Drive 发送多个附件)
Distributing Google Apps Scripts for Sheets in your company network(在您的公司网络中分发适用于表格的 Google Apps 脚本)
Upload file to my google drive from anyone using javascript(使用 javascript 将文件从任何人上传到我的谷歌驱动器)
quot;Shared Drivequot; support in Google Apps Script(“共享驱动器Google Apps 脚本中的支持)
Angular 2+ HTTP POST and GDrive API. Resumable file upload with name(Angular 2+ HTTP POST 和 GDrive API.带名称的可恢复文件上传)