利用electron.js 把 手机App “每日一文” PC端化

本文是使用了Electron.js 构建一个 Pc端 的 “每日一文”
不把UI都复刻过来,只是把功能相应地实现一下。

DEMO介绍

  1. 应用跟手机端的“每日一文”差不多,其实这APP也是用了它的API接口

  2. 实现了的功能:
    2.1 打开程序自动获取一篇文章,以及获取到其作者信息(信息来源于百度百科)
    2.2 可以保存喜欢的文章到本地(/saveArticles)
    2.3 可以手动获取随机一篇文章

  3. 未完成 :
    长按保存按钮进行文章另存为的操作

效果图

文章一览.png
作者.png
功能按钮.png

实现

用到的轮子有:

  1. Button.css - 一个高度可定制的、免费并且开源的按钮 CSS 样式库
    Button.css.png
  1. font-awesome -The iconic font and CSS toolkit
  1. jQuery

因为就一个单页面应用,我也就不把style另外拎出来了(虽然不利于后期重构和维护),但对于一个一两百行的小DEMO而言,我就懒一点了。
为了能看清楚代码结构,我就把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; /*这里是说明调用来的字体名字*/ 
    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;
    }

    /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/  
    ::-webkit-scrollbar  
    {  
        width: 10px;   
        background-color: #F5F5F5;  
    }  
      
    /*定义滚动条轨道 内阴影+圆角*/  
    ::-webkit-scrollbar-track  
    {  
      border-radius: 10px;
      background-color: #f9f9f9;
    }  
      
    /*定义滑块 内阴影+圆角*/  
    ::-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;  
    }

    /*文章后的点赞、收藏、保存 按钮*/
    .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 - 页面脉络结构

<html>
  <head>...</head>
  <body>
    <!-- <h1>随机一文</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]
;

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

          //获取文章的标题、内容、作者
          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="未找到此作者相关信息";
                return false;
            }
            else if (authorres.text=='{"errno":2}') {
                authorName.innerText=search_author;
                authorDes.innerText="未找到此作者相关信息";
                return false;
            }
            else{

                //将JSON字符串转为对象
                var authorInfo=eval("text="+authorres.text);
                // console.log(authorInfo);

                //为图片框设置属性
                $('.authorAvatar-img').attr({
                    src:authorInfo.image,
                    alt:authorInfo.title
                });

                //将作者相关信息填充到DOM中
                authorName.innerText=authorInfo.title;
                authorDes.innerText=authorInfo.abstract;
            }
          });
}

//页面加载时获取文章
getRandomArticle();


//按键监听
//
//按钮:更换文章
$('#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");
});

//长按进行文章另存为的操作-未完成
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里面添加上 "打开保存文件对话框的" 监听

//保存文章的监听
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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容