res/js/frame-link.js (view raw)
1// Melo-tech Frame Link Management System 3.2
2// This script updates the URL on each page, allowing you to share and bookmark frameset and iFrame links!
3// Feel free to steal this code!
4// Get help here - https://forum.melonking.net/index.php?topic=115
5
6// oO How to use this code Oo
7// 1. Add '<script src="https://melonking.net/scripts/frame-link.js"></script>' to your <head>.
8// 2. Add 'id="mainframe"' to your main iFrame or Frame window.
9// Optional: Create a second <script></script> section AFTER you link the frame-link.js
10// Optional: add 'updateTitle = false;' if you want to disable title updating. (Default is true)
11// Optional: add 'titlePrefix = "My Site ";' if you want to add a prefix to your titles. (Default is none)
12// Optional: add 'pageParam = "z";' if you want to change the url path of your pages. (Default is z)
13// Optional: if you use a hitCounter like GoatCounter add 'hitCounterFunction = function () { XXX MY HIT COUNTER CODE }', this function will automaticly be called each time someone click a page, so you can log per page hits within your frame.
14// See https://melonking.net/melon.html for a working example! GOOD LUCK!
15
16var mainFrame;
17var firstLoad = true;
18var updateTitle = true;
19var pageParam = "z";
20var titlePrefix = "";
21var hitCounterFunction = undefined;
22
23//Event to handle first page load - Also sets up the mainFrame
24window.addEventListener("DOMContentLoaded", (e) => {
25 mainFrame = document.getElementById("mainframe");
26 mainFrame.addEventListener("load", updateHistory, false);
27 setMainFrame();
28});
29
30//Event to handle back button presses
31window.addEventListener("popstate", function (e) {
32 if (e.state !== null) {
33 setMainFrame();
34 }
35});
36
37//Checks to see if a page parameter exists and sets the mainframe src to that page.
38function setMainFrame() {
39 let params = new URLSearchParams(window.location.search);
40 let page = params.get(pageParam);
41 if (page != null) {
42 mainFrame.src = page;
43 }
44}
45
46//Updates the browser history with the current page, causing the URL bar to update.
47function updateHistory() {
48 let title = titlePrefix + mainFrame.contentDocument.title;
49
50 // Stops the page getting into an infinate loop reloading itself.
51 if (firstLoad) {
52 firstLoad = false;
53 if (updateTitle) {
54 document.title = title;
55 }
56 if (hitCounterFunction != undefined) {
57 hitCounterFunction();
58 }
59 return;
60 }
61
62 history.replaceState(null, "", "?" + pageParam + "=" + mainFrame.contentWindow.location.pathname);
63
64 if (updateTitle) {
65 document.title = title;
66 }
67
68 //Save a hit - Optionally run this if a hit counter has been defined.
69 if (hitCounterFunction != undefined) {
70 hitCounterFunction();
71 }
72}