JSDOM dom.serialize()方法将代码从head标签移动到body标签

时间:2019-05-30 10:52:54

标签: html node.js jsdom

我正在使用JSDOM自定义node.js中的现有HTML文件。但是,即使在使用fs.readFileSync()将HTML文件输入到JSDOM并立即对其进行序列化之后,它也会将meta,title,link等代码从head标签移出。我真的很感谢您的帮助。这是我的代码示例:

Node.js:

function renderMain() {
  let htmlSource = fs.readFileSync(__dirname + "/main.html", "utf8");
  let dom = new JSDOM(htmlSource);
  dom.window.document.querySelector("#navbarHeader").innerHTML = templates.navbarMenu;
  return dom.serialize();
}

HTML:

<!DOCTYPE html>
<html lang="tr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>CANMAKSAN - CANVision®</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="public/css/styles.css" rel="stylesheet">
  </head>
  <body>
    <div class="collapse bg-dark" id="navbarHeader"></div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script>window.jQuery || document.write('<script src="/docs/4.3/assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
    <script src="https://getbootstrap.com/docs/4.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
  </body>
</html>

这是序列化后的结果html:

<html lang="tr"><head></head><body>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>CANMAKSAN - CANVision®</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="css/styles.css" rel="stylesheet">

0 个答案:

没有答案