簡體   English   中英

如何在BrowserWindow(Electron)中打開markdown文件?

[英]How do I open a markdown file in a BrowserWindow (Electron)?

我正在嘗試擴展一個電子項目。 我有一個新的BrowserWindow(基本上是瀏覽器中的新選項卡),其中應包含Documention。 該文檔是用markdown編寫的,所以我想知道如何在該BrowserWindow中打開我的markdown文件...

基本上,我只需要一種在運行時將markdownfile轉換為網頁的方法。

您將需要節點模塊fs來打開文件,並且有一個名為標記的js庫-在npm中查找。 渲染降價。

更新-這是一個最小的電子應用示例,已在0.37.8電子上進行了測試。

//start - package.json:
{
  "name": "mini-md-example",
  "version": "0.1.0",
  "description": "A small Electron application to open/display a markdown file",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron-prebuilt": "^0.37.7", 
    "marked": "^0.3.5"
  }
}
//:end - package.json

//start - main.js:
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const fs = require('fs');
var dialog = require('dialog') 
var path = require('path')
var defaultMenu = require('./def-menu-main')
var Menu = require('menu')
const {ipcMain}  = electron;

// 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: 999, height: 800})

  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/index.html`)

  // 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', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X 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 OS X 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()
  }
})

var OpenFile = function() { 
 dialog.showOpenDialog(mainWindow, {
  filters: [{name: 'Markdown', extensions: ['md', 'markdown']}],
  properties: ['openFile']
 }, function(paths) {
  if (!paths) return false; 
  var fPath = paths[0];
  var fName = path.basename(fPath);
  var fData = fs.readFileSync(fPath, 'utf8'); 

  mainWindow.webContents.send('file-open', fPath, fName, fData);

 })
}

var SendEvent = function(name) {
 return function() {mainWindow.webContents.send(name);};
};

  // Get template for default menu 
var menu = defaultMenu()

  // Add my very own custom FILE menu 

  menu.splice(0, 0, {
    label: 'File',
    submenu: [
      {
        label: 'Open',
        accelerator: "CmdOCtrl+O",
        click: OpenFile
      },
    ]
  })
  // Set top-level application menu, using modified template 
  Menu.setApplicationMenu(Menu.buildFromTemplate(menu));
//:end - main.js

//start - index.html:
<!DOCTYPE html>
<html>
    <body>
        <div id="content"></div>

        <script>
        var marked = require('marked')
        var ipc = require('electron').ipcRenderer
            ipc.on('file-open', function(event, fPath, filename, filedata) 
            {
                document.getElementById('content').innerHTML = marked(filedata)  ;       
            })

        </script>   
    </body>
</html>
//:end - index.html

//start - def-menu-main.js:
var electron = require('electron')  // this should work if you're in the electron environment
//var app = electron.remote.app
// original app var calls remote as if this is used in a renderer, but for me menus are a main app thing 
var app = electron.app

var shell = electron.shell

module.exports = function() {

  var template = [
    {
      label: 'View',
      submenu: [
        {
          label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click: function(item, focusedWindow) {
            if (focusedWindow)
              focusedWindow.reload();
          }
        },
        {
          label: 'Toggle Full Screen',
          accelerator: (function() {
            if (process.platform === 'darwin')
              return 'Ctrl+Command+F';
            else
              return 'F11';
          })(),
          click: function(item, focusedWindow) {
            if (focusedWindow)
              focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
          }
        },
        {
          label: 'Toggle Developer Tools',
          accelerator: (function() {
            if (process.platform === 'darwin')
              return 'Alt+Command+I';
            else
              return 'Ctrl+Shift+I';
          })(),
          click: function(item, focusedWindow) {
            if (focusedWindow)
              focusedWindow.toggleDevTools();
          }
        },
      ]
    },
    {
      label: 'Window',
      role: 'window',
      submenu: [
        {
          label: 'Minimize',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: 'Close',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        },
      ]
    },
    {
      label: 'Help',
      role: 'help',
      submenu: [
        {
          label: 'Learn More',
          click: function() { shell.openExternal('http://electron.atom.io') }
        },
      ]
    },
  ];

  if (process.platform === 'darwin') {
    var name = app.getName();
    template.unshift({
      label: name,
      submenu: [
        {
          label: 'About ' + name,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide ' + name,
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'Command+Shift+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click: function() { app.quit(); }
        },
      ]
    });
    var windowMenu = template.find(function(m) { return m.role === 'window' })
    if (windowMenu) {
      windowMenu.submenu.push(
        {
          type: 'separator'
        },
        {
          label: 'Bring All to Front',
          role: 'front'
        }
      );
    }
  }

  return template;
}
//:end - def-menu-main.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM