-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreload.js
More file actions
35 lines (34 loc) · 1.98 KB
/
Copy pathpreload.js
File metadata and controls
35 lines (34 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const { contextBridge, ipcRenderer, webUtils } = require('electron');
const { pathToFileURL } = require('url');
// 在 preload 里加载 highlight.js(渲染进程关闭了 nodeIntegration),common 子集覆盖约 40 种常用语言
const hljs = require('highlight.js/lib/common');
contextBridge.exposeInMainWorld('api', {
openFile: () => ipcRenderer.invoke('file:open'),
readFile: (filePath) => ipcRenderer.invoke('file:read', filePath),
// Electron 32+ 移除了 File.path,拖放的文件路径要通过 webUtils 获取(必须在 preload 调用)
getPathForFile: (file) => webUtils.getPathForFile(file),
saveFile: (filePath, content) => ipcRenderer.invoke('file:save', filePath, content),
saveFileAs: (content, suggestedName) => ipcRenderer.invoke('file:save-as', content, suggestedName),
exportHtml: (bodyHtml, title, suggestedName) => ipcRenderer.invoke('export:html', bodyHtml, title, suggestedName),
exportPdf: (bodyHtml, title, suggestedName) => ipcRenderer.invoke('export:pdf', bodyHtml, title, suggestedName),
print: (bodyHtml, title) => ipcRenderer.invoke('doc:print', bodyHtml, title),
confirmDiscard: (message) => ipcRenderer.invoke('dialog:confirm', message),
setDirty: (dirty) => ipcRenderer.send('doc:dirty-changed', dirty),
setLang: (lang) => ipcRenderer.send('settings:lang', lang),
closeAfterSave: () => ipcRenderer.send('app:close-after-save'),
onDocLoad: (cb) => ipcRenderer.on('doc:load', (event, data) => cb(data)),
onMenu: (cb) => ipcRenderer.on('menu', (event, action) => cb(action)),
onSaveThenClose: (cb) => ipcRenderer.on('app:save-then-close', () => cb()),
// 把文档的绝对路径转成 file:// URL,渲染进程用它解析 Markdown 里的相对图片路径
pathToFileUrl: (p) => pathToFileURL(p).href,
highlight: (code, lang) => {
try {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(code, { language: lang }).value;
}
return hljs.highlightAuto(code).value;
} catch {
return null;
}
}
});