Hexo -46- encrypt 加密需要 JS 文件的 html 元素

本文最后更新于:2023年4月15日 晚上

使用 Hexo-Blog-Encrypt 插件加密博客使用起来是分方便,大多数情况还是可以正确显示的,但是使用过程中发现需要 引入 JS 文件展示的内容无法正确显示,本文记录解决方案。

问题描述

使用 hexo-blog-encrypt 插件加密文章时不会帮我们引入 js 文件,导致引入 html 元素时找不到需要的 js 函数:

问题原因

这个问题是开发人员已知的问题,被归结为静态页面本身的短板,官方给出的解决方案时在文章末尾加入 Callback 函数,我尝试过将整个 js 文件的内容当做 Callback 添加到末尾也没起作用。

但是官方给了一个 TOC 显示问题的解决方案启发了我:

If you has a post with TOC, you should change the code of your template. Take the default theme ‘landscape’ as an example:

  • You should find the article.ejs file located at hexo/themes/landscape/layout/_partial/article.ejs.
  • Find the code like <% post.content %>, which is usually at line 30.
  • Replace the <% post.content %> with the following code block:
1
2
3
4
5
6
7
8
9
10
11
<% if(post.toc == true){ %>
<div id="toc-div" class="toc-article" <% if (post.encrypt == true) { %>style="display:none" <% } %>>
<strong class="toc-title">Index</strong>
<% if (post.encrypt == true) { %>
<%- toc(post.origin, {list_number: true}) %>
<% } else { %>
<%- toc(post.content, {list_number: true}) %>
<% } %>
</div>
<% } %>
<%- post.content %>

也就是说,加密不会涉及模板的功能,因此如果我们把 js 文件放在模板里面加载,那就可以绕过加密解密流程加载 js 了。

解决方案

准备 js 文件

这里我就以我当前的 echart 图标显示的问题为例,该功能需要引入 echarts.min.jsecharts-gl.min.js 文件,首先我将他们占为己有,放在自己的服务器上,得到文件地址:

1
2
https://101.43.39.125/HexoFiles/js/echarts/v5/echarts.min.js
https://101.43.39.125/HexoFiles/js/echarts/v5/echarts-gl.min.js

修改主题模板

修改主题模板,我用的 fluid 主题,修改文件位置:

1
Hexo\themes\fluid\layout\post.ejs

在开头添加一段代码:

1
2
3
4
<% if (page.echart){ %>
<script type="text/javascript" src="https://101.43.39.125/HexoFiles/js/echarts/v5/echarts.min.js"></script>
<script type="text/javascript" src="https://101.43.39.125/HexoFiles/js/echarts/v5/echarts-gl.min.js"></script>
<% } %>

表示的含义很简单,只要文章头中设置了 echart 的值,那么就加载这两个 js 文件,这个行为和正文无关。

修改文章头

我这篇加密的文章头为:

1
2
3
4
5
6
7
8
title: Hexo -46- encrypt 加密需要 JS 文件的 html 元素
mathjax: false
date: 2023-04-12 10:26:43
tags: [Hexo ,Website]
categories: [Hexo ,Website]
password: zywvvd
echart: true
message: 密码是 zywvvd

便是开启了 echart 预加载功能,今后有需要用到 echart 并且需要加密的地方,就得麻烦一点配置一下这个头了,好处是在正文中不用再次引入 js 了。

示例效果

参考资料



文章链接:
https://www.zywvvd.com/notes/hexo/website/46-encrypt-echart-test/encrypt-echart-test/


Hexo -46- encrypt 加密需要 JS 文件的 html 元素
https://www.zywvvd.com/notes/hexo/website/46-encrypt-echart-test/encrypt-echart-test/
作者
Yiwei Zhang
发布于
2023年4月12日
许可协议