Electron包裝網站的問題

原文鏈接

原文鏈接

Preface

最近嘗試了很多不錯的在線工具,只是每次都要進入網站,有點麻煩,於是想到之前瞭解過的electron,嘗試一下打包成本地應用。

Contents

1.下載所有源文件

通過開發者工具,'copy all as Node.js fetch',然後配合 node-fetch 庫,將需要用到的資源下載到本地:

const fs = require('fs')
const fetch = require('node-fetch');

function checkAndWrite(filepath,res) {
   console.log("ok , here it is:",filepath);
   //todo create directory loop  
   const dirpath = filepath.substr(0,filepath.lastIndexOf("/"));
   console.log(dirpath);
   if(!fs.existsSync(dirpath)){
       fs.mkdir(dirpath,{recursive:true},(err)=>{
           if(err != null) {
               console.log("mkdir err:",err);
               return;
           }
           const dest = fs.createWriteStream(filepath);
           res.body.pipe(dest);
       })
       return;
   }

   const dest = fs.createWriteStream(filepath);
   res.body.pipe(dest);
}
// 這個是主頁
fetch("https://material.io/resources/color/", {
 "headers": {
   "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
   "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
   "cache-control": "no-cache",
   "pragma": "no-cache",
   "sec-ch-ua": "\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"92\"",
   "sec-ch-ua-mobile": "?0",
   "sec-fetch-dest": "document",
   "sec-fetch-mode": "navigate",
   "sec-fetch-site": "none",
   "sec-fetch-user": "?1",
   "upgrade-insecure-requests": "1",
   "cookie": "_ga=GA1.2.682063148.1629876102; _gid=GA1.2.1595024389.1629876102"
 },
 "referrerPolicy": "strict-origin-when-cross-origin",
 "body": null,
 "method": "GET",
 "mode": "cors"
}).then(res=>{
   checkAndWrite('./html/main.html',res)
})

// 這個是其中的一個資源
fetch("https://material.io/resources/color/styles/vendor-bab328c105.css", {
 "headers": {
   "accept": "text/css,*/*;q=0.1",
   "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
   "cache-control": "no-cache",
   "pragma": "no-cache",
   "sec-ch-ua": "\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"92\"",
   "sec-ch-ua-mobile": "?0",
   "sec-fetch-dest": "style",
   "sec-fetch-mode": "no-cors",
   "sec-fetch-site": "same-origin",
   "cookie": "_ga=GA1.2.682063148.1629876102; _gid=GA1.2.1595024389.1629876102; _gat=1"
 },
 "referrer": "https://material.io/resources/color/",
 "referrerPolicy": "strict-origin-when-cross-origin",
 "body": null,
 "method": "GET",
 "mode": "cors"
}).then(res=>{
   checkAndWrite('./html/styles/vendor-bab328c105.css',res)
})

2.在electron中加載

mainWindow = new BrowserWindow({width: 1000, height: 800, webPreferences:{webSecurity:false}})

mainWindow.loadURL(url.format({
    pathname:path.join(__dirname,"/html/main.html"),
    protocol: "file",
    slashes: true
}))

3. 注意的點

  • main.html 下載下來之後,需要將對應的資源路徑改爲*相對的本地路徑
  • google-analysis相關的東西都去掉了,應該是用不上的
  • 其他非https://material.io域名下的文件也要下載下來,並且到對應的文件裏面去修改相對路徑

效果圖


源代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章