| 1 | import { webContents, WebContents } from 'electron'; |
| 2 | import { ICookieParams, ICreateBrowserWindowParams } from './browserWindow'; |
| 3 | |
| 4 | export default class BrowserWindowItem { |
| 5 | webViewId: number; |
| 6 | webview!: WebContents; |
| 7 | |
| 8 | constructor(webViewId: number) { |
| 9 | this.webViewId = webViewId; |
| 10 | } |
| 11 | |
| 12 | /** |
| 13 | * 创建 webview |
| 14 | * @param data |
| 15 | */ |
| 16 | async create(data: ICreateBrowserWindowParams) { |
| 17 | this.webview = webContents.fromId(this.webViewId)!; |
| 18 | if (!this.webview) |
| 19 | return console.error(`无法找到id为 ‘${this.webViewId}’ 的webview`); |
| 20 | |
| 21 | // this.webview.openDevTools(); |
| 22 | // this.webview.setWindowOpenHandler((data) => { |
| 23 | // console.log(data.url); |
| 24 | // return { |
| 25 | // action: 'deny', |
| 26 | // }; |
| 27 | // }); |
| 28 | if (data.cookieParams) { |
| 29 | await this.setCookies(data.cookieParams); |
| 30 | } |
| 31 | return true; |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * 设置cookies |
| 36 | * @param cookieParams |
| 37 | */ |
| 38 | async setCookies(cookieParams: ICookieParams) { |
| 39 | for (const v of cookieParams.cookies) { |
| 40 | let url: string; |
| 41 | if (v.domain![0] === '.') { |
| 42 | url = `https://www.${v.domain?.substring(1, v.domain?.length)}`; |
| 43 | } else { |
| 44 | url = `https://${v.domain}`; |
| 45 | } |
| 46 | await this.webview.session.cookies.set({ |
| 47 | url: url, |
| 48 | name: v.name, |
| 49 | value: v.value, |
| 50 | domain: v.domain, |
| 51 | path: v.path, |
| 52 | secure: v.secure, |
| 53 | httpOnly: v.httpOnly, |
| 54 | }); |
| 55 | } |
| 56 | return true; |
| 57 | } |
| 58 | } |
| 59 |