Skip to content

tocbot fails to initialize when using id="<global | exports | module>" #385

@cotes2020

Description

@cotes2020

Hi, thanks for the great project!

I ran into an issue where tocbot fails to initialize when the page contains an element with id="global". The browser console throws the following error:

Uncaught ReferenceError: tocbot is not defined
A simple example

Live demo

https://tocbot-debug.netlify.app/

Source code

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tocbot Example</title>
    <!-- tocbot -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tocbot@4.36.2/dist/tocbot.min.css">
    <script src="https://cdn.jsdelivr.net/npm/tocbot@4.36.2/dist/tocbot.min.js" defer></script>
  </head>
  <body>
    <header>
      <h1>Tocbot Example</h1>
      <p>This is an example showing tocbot initialization failure.</p>
    </header>
    <div id="toc"></div>
    <hr>
    <div class="content">
      <h2 id="global">Global</h2>
      <p>Content for section 1...</p>
      <h2 id="section2">Section 2</h2>
      <p>Content for section 2...</p>
      <h3 id="section1-1">Section 1.1</h3>
      <p>Content for section 1.1...</p>
    </div>
    <script>
      document.addEventListener('DOMContentLoaded', () => {
        tocbot.init({
          tocSelector: '#toc',
          contentSelector: '.content',
          headingSelector: 'h2, h3, h4',
          orderedList: false,
        });
      });
    </script>
  </body>
</html>

This seems to happen because id="global" conflicts with the window.global reference in some environments, especially in bundlers or browsers that auto-expose global variables. I'm using defer to load tocbot.min.js for performance reasons, if I remove defer it goes back to normal.

Would it be possible to guard against this kind of global name conflict, or perhaps mention it in the documentation?

Thanks again!


Update:

As long as the following two conditions are met:

  1. The HTML page has an id that is one of the keywords: global, exports, or module.

  2. tocbot.js is executed after the page has fully loaded (e.g., using the defer attribute).

It will cause tocbot initialization to fail, meaning the current logic cannot correctly distinguish between a node.js and browser environment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions