Electron App 获取 Webview 页面 cookie

Electron App 获取 Webview 页面 cookie

业务需要,要用webview来获取加载页面的cookie;
有两种常用的写法:

  1. 根据partition创建session来获取
    引入webview,在当前最新的electron版本中(10.1.5),webview并不是默认支持的,需要在主进程中手动开启,开启参数为如下:
// Create the browser window.
  mainWindow = new BrowserWindow({
    
    
    width: 800,
    height: 600,
    webPreferences:{
    
    
      webviewTag: true, //开启webview支持
      nodeIntegration: true, //开启渲染页面的node环境
    }
  });
//设置完毕过后,再引入webview标签
<webview src="https://github.com" partition="persist:github"></webview>
//获取cookie信息
var ses = session.fromPartition('persist:github');
  ses.cookies.get({
    
    url:'https://github.com'}).then(function(cookies,error){
    
    
      console.log(cookies);
  });

这种写法需要webview的partition属性相配合,session实例会根据这个属性值来返回/创建对应的session对象实例

  1. 使用Electron session 模块
session.defaultSession.cookies.get({
    
    url:'https://github.com'}).then(function(cookies,error){
    
    
      console.log(cookies);
  });

url为被获取cookie的网址,具体api可移步Electron session 模块

Guess you like

Origin blog.csdn.net/qq_34995862/article/details/109743795