注入器

注入器用於將靜態程式碼片段新增到產生的 HTML 檔案的 <head> 或/和 <body> 中。Hexo 會在執行 after_render:html 過濾器之前執行注入器。

概要

hexo.extend.injector.register(entry, value, to);

entry <string>

程式碼將被注入到 HTML 中的位置。

支援以下值

  • head_begin: 將程式碼片段注入到 <head> 之後 (預設)。
  • head_end: 將程式碼片段注入到 </head> 之前。
  • body_begin: 將程式碼片段注入到 <body> 之後。
  • body_end: 將程式碼片段注入到 </body> 之前。

value <string> | <Function>

支援返回字串的函式。

要注入的程式碼片段。

to <string>

程式碼片段將被注入到哪個頁面。

  • default: 注入到每個頁面 (預設)。
  • home: 僅注入到首頁 (is_home() 輔助函式為 true 的頁面)
  • post: 僅注入到文章頁面 (is_post() 輔助函式為 true 的頁面)
  • page: 僅注入到頁面 (is_page() 輔助函式為 true 的頁面)
  • archive: 僅注入到封存頁面 (is_archive() 輔助函式為 true 的頁面)
  • category: 僅注入到分類頁面 (is_category() 輔助函式為 true 的頁面)
  • tag: 僅注入到標籤頁面 (is_tag() 輔助函式為 true 的頁面)
  • 也可以使用自訂版面配置名稱,請參閱寫作 - 版面配置

還有其他內部函式,請參閱 hexojs/hexo#4049 以取得更多詳細資訊。

範例

const css = hexo.extend.helper.get("css").bind(hexo);
const js = hexo.extend.helper.get("js").bind(hexo);

hexo.extend.injector.register(
"head_end",
() => {
return css(
"https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css",
);
},
"music",
);

hexo.extend.injector.register(
"body_end",
'<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">',
"music",
);

hexo.extend.injector.register("body_end", () => {
return js("/js/jquery.js");
});

上面的設定會將 APlayer.min.css (<link> 標籤) 注入到版面配置為 music 的任何頁面的 </head> 中,並將 APlayer.min.js (<script> 標籤) 注入到這些頁面的 </body> 中。此外,jquery.js (<script> 標籤) 將被注入到每個產生的頁面的 </body> 中。

存取使用者設定

使用以下任何選項

const css = hexo.extend.helper.get("css").bind(hexo);

hexo.extend.injector.register("head_end", () => {
const { cssPath } = hexo.config.fooPlugin;
return css(cssPath);
});
index.js
/* global hexo */

hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo));
lib/inject.js
module.exports = function () {
const css = this.extend.helper.get("css");
const { cssPath } = this.config.fooPlugin;
return css(cssPath);
};
lib/inject.js
function injectFn() {
const css = this.extend.helper.get("css");
const { cssPath } = this.config.fooPlugin;
return css(cssPath);
}

module.exports = injectFn;
index.js
/* global hexo */

hexo.extend.injector.register("head_end", require("./lib/inject")(hexo));
lib/inject.js
module.exports = (hexo) => () => {
const css = hexo.extend.helper.get("css").bind(hexo);
const { cssPath } = hexo.config.fooPlugin;
return css(cssPath);
};
lib/inject.js
const injectFn = (hexo) => {
const css = hexo.extend.helper.get("css").bind(hexo);
const { cssPath } = hexo.config.fooPlugin;
return css(cssPath);
};

module.exports = (hexo) => injectFn(hexo);