MediaWiki:Common.js

From WikiPhone
Revision as of 21:26, 10 November 2025 by CaptainChris (talk | contribs)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */


document.addEventListener("DOMContentLoaded", () => {
  const iframe = document.querySelector('iframe[key="wikiphone"]');
  if (!iframe) return;

  iframe.style.display = "block";
  iframe.style.width = "100vw";
  iframe.style.maxWidth = "100%";
  iframe.style.marginLeft = "calc(-50vw + 50%)";
  iframe.style.border = "none";
  iframe.style.overflow = "hidden";
  iframe.setAttribute("scrolling", "no");

  const setH = (h) => {
    const height = Math.max(200, Math.floor(h || 0));
    if (iframe.style.height !== height + "px") {
      iframe.style.height = height + "px";
    }
  };

  function trySameOriginWiring() {
    try {
      const doc = iframe.contentDocument || iframe.contentWindow?.document;
      if (!doc) return false; // not ready yet / cross-origin

      const ro = new ResizeObserver(() => {
        const b = doc.body;
        const e = doc.documentElement;
        const h = Math.max(
          b.scrollHeight,
          b.offsetHeight,
          e.clientHeight,
          e.scrollHeight,
          e.offsetHeight
        );
        setH(h);
      });
      ro.observe(doc.documentElement);
      ro.observe(doc.body);

      const kick = () => {
        const b = doc.body;
        const e = doc.documentElement;
        const h = Math.max(
          b.scrollHeight,
          b.offsetHeight,
          e.clientHeight,
          e.scrollHeight,
          e.offsetHeight
        );
        setH(h);
      };
      iframe.addEventListener("load", kick, { once: true });
      kick();

      window.addEventListener("resize", kick);
      return true;
    } catch (e) {
      return false;
    }
  }

  function wireCrossOriginMessaging() {
    window.addEventListener("message", (event) => {
      const data = event.data;
      if (!data || typeof data !== "object") return;
      if (data.type === "wikiphone:height" && typeof data.height === "number") {
        setH(data.height);
      }
    });

    const pingChild = () => {
      iframe.contentWindow?.postMessage({ type: "wikiphone:getHeight" }, "*");
    };

    iframe.addEventListener("load", () => {
      setH(400); // give it a starter height so page isn’t tiny
      let count = 0;
      const t = setInterval(() => {
        pingChild();
        if (++count >= 10) clearInterval(t);
      }, 500);
    });
  }

  const wired = trySameOriginWiring();
  if (!wired) wireCrossOriginMessaging();
});