Hexo网站在全部的html中插入谷歌广告代码、注入自定义js脚本或css样式、源码片段

Hexo网站在全部的html中插入谷歌广告代码、注入自定义js脚本或css样式、源码片段


开发hexo插件,算是一种方法。但是需要阅读较多文档,要对接hexo的api。

我想的办法是,懒得读hexo文档,直接写nodejs代码,只需实现:

  1. 读取hexo 输出的全部html文件
  2. 通过nodejs修改html字符串
  3. 一切完成,所以的html都可以注入我想插入的代码


代码示例:

build\htmlFilesAddAD.js

/*
把hexo输出的全部html文件, 每一个html文件都插入谷歌广告的js脚本
*/
const path = require('path');
let inputPath = path.join(__dirname, '../public')

async function main() {
  let files = await getFilesByExtAndPath('.html', inputPath);
  console.log('插入谷歌广告脚本, html文件总数:' + files.length);
  // console.log(files)

  const fs = require('fs-extra')
  // 谷歌广告js
  const AD = getAdHtml();

  for (let index = 0; index < files.length; index++) {
    const file = files[index];
    let path2 = path.join(inputPath, file)
    let data = await fs.readFile(path2, { encoding: 'utf-8' })
    // data = data + insertAD
// 把插入的代码放在 head 中间
    data = data.replace('<head>', '<head>' + AD + '\n');

    await fs.writeFile(path2, data)
  }

  console.log('处理完成', new Date())
}

main()

// let files = await getFilesByExtAndPath('.xlsx', 'c:/')
function getFilesByExtAndPath(ext, path) {
  const glob = require('glob-promise')
  return glob('**/*' + ext, { cwd: path })
}

function getAdHtml() {
  let GoogleAd = `<script data-ad-client="xxId" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>`
  return GoogleAd
}


程序使用的npm开源包

"devDependencies": {
    "fs-extra": "9.1.0",
    "glob": "7.1.6",
    "glob-promise": "4.1.0"
  }