利用electron.js 把 手機(jī)App “每日一文” PC端化

本文是使用了Electron.js 構(gòu)建一個 Pc端 的 “每日一文”
不把UI都復(fù)刻過來,只是把功能相應(yīng)地實(shí)現(xiàn)一下。

DEMO介紹

  1. 應(yīng)用跟手機(jī)端的“每日一文”差不多,其實(shí)這APP也是用了它的API接口

  2. 實(shí)現(xiàn)了的功能:
    2.1 打開程序自動獲取一篇文章,以及獲取到其作者信息(信息來源于百度百科)
    2.2 可以保存喜歡的文章到本地(/saveArticles)
    2.3 可以手動獲取隨機(jī)一篇文章

  3. 未完成 :
    長按保存按鈕進(jìn)行文章另存為的操作

效果圖

文章一覽.png
作者.png
功能按鈕.png

實(shí)現(xiàn)

用到的輪子有:

  1. Button.css - 一個高度可定制的、免費(fèi)并且開源的按鈕 CSS 樣式庫
    Button.css.png
  1. font-awesome -The iconic font and CSS toolkit
  1. jQuery

因?yàn)榫鸵粋€單頁面應(yīng)用,我也就不把style另外拎出來了(雖然不利于后期重構(gòu)和維護(hù)),但對于一個一兩百行的小DEMO而言,我就懶一點(diǎn)了。
為了能看清楚代碼結(jié)構(gòu),我就把index.html部分抽出來貼吧:

index.html - <head>部分

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>遇文</title>
    <script>window.$ = window.jQuery = require('jquery');</script>
    <link rel="stylesheet" href="css/buttons.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">

    <style> 
      ... 
    </style>
</head>

index.html -style 樣式

    <style>
    @font-face { 
    font-family: NotoSansHans-Light; /*這里是說明調(diào)用來的字體名字*/ 
    src: url('./assets/NotoSansHans-Light.otf'); /*這里是字體文件路徑*/ 
    } 
    @font-face{
      font-family:NotoSansHans-Regular;
      src:url('./assets/NotoSansHans-Regular.otf');
    }
    @font-face{
      font-family: Title;
      src:url('./assets/Title.ttf');
    }
    /*是否控制開啟透明*/
    body{
      -webkit-app-region: drag;
    }
    button,.button{
      -webkit-app-region: no-drag;
    }
    body,#DailyArticle{
      margin:0;
    }

    /*定義滾動條高寬及背景 高寬分別對應(yīng)橫豎滾動條的尺寸*/  
    ::-webkit-scrollbar  
    {  
        width: 10px;   
        background-color: #F5F5F5;  
    }  
      
    /*定義滾動條軌道 內(nèi)陰影+圓角*/  
    ::-webkit-scrollbar-track  
    {  
      border-radius: 10px;
      background-color: #f9f9f9;
    }  
      
    /*定義滑塊 內(nèi)陰影+圓角*/  
    ::-webkit-scrollbar-thumb  
    {  
      border-radius: 4px;
      -webkit-box-shadow: 0 0 7px rgba(0, 0, 0, 0.24);
      background-color: rgb(79, 181, 255);
    }  
    .DailyArticle{
    background: #F1F2F1;
    background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
    font-family: 'NotoSansHans-Light';
    padding: 1em;
    font-size: 1.2em;
    line-height: 2.4em;
    text-indent: 2em;
    color: #424242;
    text-shadow: 1px 1px 14px rgba(189, 189, 189, 0.48);
    border: 1px solid #d4d4d4;
    border-radius: 6px;
    box-shadow: 1px 1px 20px rgb(220, 220, 220);
    margin: 1em;
    transition: .3s all ease-in-out;
    }
    .DailyArticle:hover{
      box-shadow: 1px 1px 20px rgb(185, 185, 185);
    }
    .DailyArticle hr{
      color:#afafaf;
      border-style: dashed;
      margin-top: -18px;
    }
    .articleTitle{
      font-family: 'Title';
      font-family: 'Title';
      font-size: 3em;
      margin: 1em 0;
    }
    .articleContent{
      font-family: 'NotoSansHans-Regular';
    }
    .articleFooter{
      text-align:right;
    }
    ::selection{
      background: #d6d6d6;  
    }

    /*文章后的點(diǎn)贊、收藏、保存 按鈕*/
    .handleArticle{
    margin: 5em auto;
    text-align: center;
    }
    .handleArticle button{
      width: 100px;
      height: 100px;
      font-size:2em;
      margin-right: 30px;
      transition:.3s all;
    }
    .handleArticle button:hover{
      margin-right: 50px;
    }
    .authorAvatar-img{
      max-width: 200px;
    border: 8px solid #fff;
    border-radius: 2px;
    box-shadow: 0px 5px 20px #b3b3b3;
    margin: 15px auto;
    display: block;
    }
    #text_saved{
      background-color: #dedede;
      font-size: 0.6em;
      border-radius: 5px;
      margin-top: 4em;
    }
    .refresh{
      text-align:right;
    }
    .authorName{
    font-size: 3em;
    line-height: normal;
    }
    </style>

index.html - 頁面脈絡(luò)結(jié)構(gòu)

<html>
  <head>...</head>
  <body>
    <!-- <h1>隨機(jī)一文</h1> -->


    <div id="DailyArticle" class="DailyArticle">

      <div class="articleTitle"></div>
      <hr>
      <div class="articleContent">正在獲取中...</div>
      <div class="articleFooter"></div>
      
      <div class="handleArticle">
      <button id="btn_getRandomArticle" class="button button-glow button-circle button-action button-caution"><i class="fa fa-random"></i></button>
      <button class="button button-glow button-circle button-action button-primary"><i class="fa fa-star"></i></button>
      <button id="btn_save"class="button button-glow button-circle button-primary"><i class="fa fa-floppy-o"></i></button>
      <p id="text_saved"></p>
      </div>
    </div>


    <div id="authorInfo" class="DailyArticle">
      <div class="refresh">
        <button id="btn_refresh" class="button button-raised button-action button-circle button-highlight"><i class="fa fa-refresh"></i></button>
      </div>
      <div class="authorName"></div>
      <div class="authorAvatar"><img src="" class="authorAvatar-img"alt=""></div>
      <div class="authorDes"></div>

    </div>
  </body>

  <script>
    // You can also require other files to run in this process
    require('./renderer.js')
  </script>
</html>

renderer.js


//module import

const ipc = require('electron').ipcRenderer;

var cheerio = require('cheerio'),
    superagent = require('superagent'),
    fs = require('fs'),
    path = require('path')
;
var result_list=$("#DailyArticle"),
    articleTitle=$(".articleTitle")[0],
    articleContent=$('.articleContent')[0],
    articleFooter=$('.articleFooter')[0],

    authorAvatar=$('.authorAvatar')[0],
    authorAvatarImg=$('.authorAvatar-img')[0],
    authorName=$('.authorName')[0],
    authorDes=$('.authorDes')[0]
;

//隨機(jī)獲取一篇文章
function getRandomArticle(){
    superagent
        .get('https://interface.meiriyiwen.com/article/random?dev=1')
        .end(function (err, sres) {
          if (err) throw err;

          //獲取文章的標(biāo)題、內(nèi)容、作者
          let dailyArticle=eval("text="+sres.text);
          console.log(dailyArticle);
          articleTitle.innerHTML=dailyArticle.data.title;
          articleContent.innerHTML=dailyArticle.data.content;
          articleFooter.innerHTML=dailyArticle.data.author;


          //將作者的名字傳入百度百科API獲取更多作者信息
          let search_author=articleFooter.innerText;

          //獲取作者信息
          //
          getAuthorInfo(search_author);

        });
}

//獲取作者信息
function getAuthorInfo(search_author) {
    superagent.get("http://baike.baidu.com/api/openapi/BaikeLemmaCardApi")
          .query({
            scope:103,
            format:'json',
            appid:379020,
            bk_key:search_author,
            // bk_key:'讓·季奧諾',  //test err: {}
            bk_length:600
          })
          .end(function(err,authorres){
            console.log(authorres);
            console.log(authorres.text);
            //若沒有找到作者,返回錯誤信息
            let errApiInfo={"errno":2}
            if(authorres.text=="{}"){
                authorName.innerText=search_author;
                authorDes.innerText="未找到此作者相關(guān)信息";
                return false;
            }
            else if (authorres.text=='{"errno":2}') {
                authorName.innerText=search_author;
                authorDes.innerText="未找到此作者相關(guān)信息";
                return false;
            }
            else{

                //將JSON字符串轉(zhuǎn)為對象
                var authorInfo=eval("text="+authorres.text);
                // console.log(authorInfo);

                //為圖片框設(shè)置屬性
                $('.authorAvatar-img').attr({
                    src:authorInfo.image,
                    alt:authorInfo.title
                });

                //將作者相關(guān)信息填充到DOM中
                authorName.innerText=authorInfo.title;
                authorDes.innerText=authorInfo.abstract;
            }
          });
}

//頁面加載時獲取文章
getRandomArticle();


//按鍵監(jiān)聽
//
//按鈕:更換文章
$('#btn_getRandomArticle').on('click',function(){
    getRandomArticle()

    //回到頂部
    var speed=200;
    $('body,html ').animate({scrollTop:0},speed);
    return false;
});


//按鈕:保存文章到 ../saveArticles/ 文件夾下
$('#btn_save').on("click",function(event){
    upLevelPath=path.resolve(__dirname,"..")
    saveArticlesPath=path.join(upLevelPath,"saveArticles/"+articleTitle.innerText+".txt");

    fs.exists(saveArticlesPath,function(exists){
            if(exists){
                console.log("文件已存在");
                $('#text_saved').text("文件已存在于:"+saveArticlesPath);

                return false;
            }else{
                fs.writeFile(saveArticlesPath,articleContent.innerText+articleFooter.innerText,function(err){
                    if(!err)
                        console.log("保存成功");
                        $('#text_saved').text("文本保存于:"+saveArticlesPath);
                    }
                )
            }
        }
    );
    
    console.log("save");
});

//長按進(jìn)行文章另存為的操作-未完成
var timeout;
$('#btn_save').on("mousedown",function(){
    timeout=setTimeout(function(){
        ipc.send('save-dialog');
        console.log("long click");
    },1000);
});
$('#btn_save').on("mouseup",function(){
    clearTimeout(timeout);

})


ipc.on('saved-fileDirectory', function (event, path) {
  if (!path) path = '無路徑';
  $('#text_saved').innerHTML = `選擇的路徑: ${path}`
})


//刷新按鈕:重新獲取作者信息

$('#btn_refresh').on("click",function(){
    getAuthorInfo(articleFooter.innerText);
});

在main.js里面添加上 "打開保存文件對話框的" 監(jiān)聽

//保存文章的監(jiān)聽
const ipc = require('electron').ipcMain
const dialog = require('electron').dialog

ipc.on('save-dialog', function (event) {
  defaultPath_url=url.format({
    pathname: path.join(__dirname, 'saveArticles/'),
    protocol: 'file:',
    slashes: true
  })
  const options = {
    title: '保存文本到',
    defaultPath:defaultPath_url,
    filters:[
      {name:'文本文件', extensions:['txt']}
    ]
  }

參考資料:

Electron-中文文檔,API

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容