利用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ù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,048評論 6 542
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,414評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,169評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,722評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,465評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,823評論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,813評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,000評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,554評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,295評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,513評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,722評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,125評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,430評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,237評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,482評論 2 379

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