【问题标题】:Electron set cookie电子集饼干
【发布时间】:2020-06-23 08:07:42
【问题描述】:

我是电子新手并将 Web 应用程序转换为桌面应用程序。我正在从文件系统加载页面。如果页面是从 Web 服务器提供的,Cookies 正在工作,但是当我从本地文件夹加载页面时,我无法保存它们.我在 web 中使用 document.cookie 保存 cookie。我想知道如何在 electron 中启用 file:// cookie。

问候

【问题讨论】:

  • 为什么需要来自文件系统的 cookie?
  • 我想在电子应用程序中使用网络。有没有办法做到这一点
  • 听起来像是 x-y 问题。
  • 由于 file:// 协议,我无法保存 cookie
  • Electron 9,没有任何工作,请帮助

标签: node.js electron


【解决方案1】:

按照文档完成,并使用标准。https://electronjs.org/docs/api/cookies

  const {session} = require('electron')

      // Query all cookies.
      session.defaultSession.cookies.get({}, (error, cookies) => {
        console.log(error, cookies)
      })

      // Query all cookies associated with a specific url.
      session.defaultSession.cookies.get({url: 'http://www.github.com'}, (error, cookies) => {
        console.log(error, cookies)
      })

      // Set a cookie with the given cookie data;
      // may overwrite equivalent cookies if they exist.
      const cookie = {url: 'http://www.github.com', name: 'dummy_name', value: 'dummy'}
      session.defaultSession.cookies.set(cookie, (error) => {
        if (error) console.error(error)
      })

【讨论】:

  • 我无法在 file:// 协议上保存 cookie
  • @ZahidNisar 你知道如何设置file://吗?
  • @Noitidart no 我无法将 cookie 保存在电子文件中的 file:// 中,所以我使用我的 registerStandardSchemes 加载文件
  • 哦,我现在在下面看到您的解决方案,谢谢分享!
【解决方案2】:

好吧,我想回答我的问题,以防有人遇到同样的问题。我已经通过 registerStandardSchemes 修复了 cookie 问题。示例代码如下,代码也适用于从网页保存 cookie:

protocol.registerStandardSchemes(["app"], {
    secure: true
});

在就绪事件中

protocol.registerFileProtocol('app', (request, callback) => {
    const urls = request.url.substr(6)
    const parsedUrl = url.parse(urls);
    // extract URL path
    const pathname = `.${parsedUrl.pathname}`;
    // based on the URL path, extract the file extention. e.g. .js, .doc, ...
    const ext = path.parse(pathname).ext;
    callback({
       path: path.normalize(`${__dirname}/${parsedUrl.pathname}`)
    })
}, (error) => {
    if (error) {
        console.error('Failed to register protocol');
    }
});

【讨论】:

  • 这在 Electron 5 中不再起作用。protocol.registerStandardSchemes 已被 protocol.registerSchemesAsPrivileged(customSchemes) 取代,甚至用安全的 customScheme 代替它似乎对我不起作用.我很难相信像在 web 应用程序的代码中支持 document.cookie 这样简单的事情在 Electron 中这么难,而且除了 Stackexchange 上的一些有用的帖子之外,没有任何信息。
【解决方案3】:

好的,我让它与 Electron 5 一起工作。下面是基于 @zahid-nisar 解决方案的相关位,下面是一个完整的 Electron main.js 示例,以展示它们如何组合在一起。显然,在mainWindow.loadURL('app://www/index.html'); 中更改您的应用程序的位置。

在main.js中插入的相关代码:

const { protocol } = require('electron');

protocol.registerSchemesAsPrivileged([{
    scheme: 'app',
    privileges: {
        standard: true,
        secure: true
    }
}]);

app.on('ready') 函数内部:

protocol.registerFileProtocol('app', (request, callback) => {
    const url = request.url.substr(6);
    callback({
        path: path.normalize(`${__dirname}/${url}`)
    });
}, (error) => {
    if (error) console.error('Failed to register protocol');
});

然后,在您的 createWindow 函数中,像这样加载您的应用:

mainWindow.loadURL('app://www/index.html');

最后,这是一个包含上述代码的完整示例 main.js(加上我需要的附加功能,例如 Service Worker):

// Modules to control application life and create native browser window
const {
    app,
    protocol,
    BrowserWindow
} = require('electron');
const path = require('path');

// This is used to set capabilities of the app: protocol in onready event below
protocol.registerSchemesAsPrivileged([{
    scheme: 'app',
    privileges: {
        standard: true,
        secure: true,
        allowServiceWorkers: true,
        supportFetchAPI: true
    }
}]);

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600
        //, webPreferences: {
        //     preload: path.join(__dirname, 'preload.js')
        // }
    });

    // and load the index.html of the app.
    mainWindow.loadURL('app://www/index.html');
    // DEV: Enable code below to check cookies saved by app in console log
    // mainWindow.webContents.on('did-finish-load', function() {
    //     mainWindow.webContents.session.cookies.get({}, (error, cookies) => {
    //       console.log(cookies);
    //     });
    // });

    // Open the DevTools.
    // mainWindow.webContents.openDevTools()

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
    protocol.registerFileProtocol('app', (request, callback) => {
        const url = request.url.substr(6);
        callback({
            path: path.normalize(`${__dirname}/${url}`)
        });
    }, (error) => {
        if (error) console.error('Failed to register protocol');
    });
    // Create the new window
    createWindow();
});

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') app.quit();
});

app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) createWindow();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

【讨论】:

  • 在这一行mainWindow.loadURL('app://www/index.html'); 我认为 www 是 index.html 所在的目录。我的主要问题是这应该自动加载页面吗?我在 v7.1 中没有任何运气
  • @Jaifroid 你能分享你的COOKIE URL吗? electronWindow.webContents.session.cookies.set( { url: ???????
  • @Jaifroid 现在我试试这个应用程序://C:\mypath\dist\ssw\index.html 谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 2020-04-12
  • 2015-06-06
  • 2010-09-15
  • 2016-03-21
  • 2010-10-06
相关资源
最近更新 更多