// ==UserScript== // @name UCJS: Copy Tab and Page Information (Wayback) // @description Copy tab/page URLs, titles, or both. Right-click adds the Wayback prefix. // @version 3.3 // @license MIT // @compatibility Firefox 100+ / Zen Browser // @include main // @run-at document-start // ==/UserScript== (function () { "use strict"; const { classes: Cc, interfaces: Ci } = Components; // ========================================================================= // Configuration // ========================================================================= const WAYBACK_PREFIX = "https://web.archive.org/web/"; const TAB_MENU_ID = "ucjs-copy-tab-info"; const TAB_TYPES = ["url", "title", "both"]; const PLACES_MENU_IDS = { url: "ucjs-copy-page-url", title: "ucjs-copy-page-title", both: "ucjs-copy-page-url-title" }; const CONTEXT_REQUEST_TIMEOUT = 2000; // ========================================================================= // Localization // ========================================================================= const locale = ( document.documentElement.lang || navigator.language || "en-US" ).toLowerCase(); const isPortuguese = locale.startsWith("pt"); const tabLabels = isPortuguese ? { url: ["Copiar URL da aba", "Copiar URLs das abas"], title: ["Copiar título da aba", "Copiar títulos das abas"], both: ["Copiar URL + título", "Copiar URLs + títulos das abas"] } : { url: ["Copy Tab URL", "Copy Tab URLs"], title: ["Copy Tab Title", "Copy Tab Titles"], both: ["Copy Tab URL + Title", "Copy Tab URLs + Titles"] }; const placesLabels = isPortuguese ? { url: "Copiar URL da página", title: "Copiar título da página", both: "Copiar URL + título da página" } : { url: "Copy Page URL", title: "Copy Page Title", both: "Copy Page URL + Title" }; // ========================================================================= // State // ========================================================================= let tabPopup = null; let tabContextTabs = []; let lastTabContextRequest = null; let currentTabPopupWasRightClick = false; let lastPlacesContextRequest = null; let currentPlacesPopupWasRightClick = false; let startupObserver = null; let initialized = false; // ========================================================================= // Clipboard // ========================================================================= function copyToClipboard(value) { if (!value) { return; } try { Cc["@mozilla.org/widget/clipboardhelper;1"] .getService(Ci.nsIClipboardHelper) .copyString(String(value)); console.log( "[UCJS Copy Information] Copied:", value ); } catch (error) { console.error( "[UCJS Copy Information] Clipboard error:", error ); } } // ========================================================================= // Wayback URL formatting // ========================================================================= function formatURL(url, isRightClick) { if (!url) { return ""; } // Normal click or keyboard-triggered menu: // preserve the original URL. if (!isRightClick) { return url; } // Prevent adding the Wayback prefix twice. if (url.startsWith(WAYBACK_PREFIX)) { return url; } return WAYBACK_PREFIX + url; } // ========================================================================= // Tab identification // ========================================================================= function getTabFromTarget(target) { let node = target; while (node) { if (node.localName === "tab") { return node; } if (node.matches?.("tab")) { return node; } node = node.parentNode || node.host || null; } return null; } function getContextTab(popup = tabPopup) { const trigger = popup?.triggerNode; // Prefer Firefox's actual context-menu target. return ( trigger?.tab || getTabFromTarget(trigger) || window.TabContextMenu?.contextTab || gBrowser.selectedTab ); } function getContextTabs(popup = tabPopup) { const tab = getContextTab(popup); if (!tab) { return []; } // Preserve multi-selection. if (tab.multiselected) { const selectedTabs = gBrowser.selectedTabs; if (selectedTabs?.length) { return [...selectedTabs]; } } return [tab]; } // ========================================================================= // Tab information // ========================================================================= function getTabURL(tab) { return tab.linkedBrowser?.currentURI?.spec || ""; } function getTabTitle(tab) { return ( tab.linkedBrowser?.contentTitle || tab.label || tab.getAttribute("label") || "" ); } function copyTabs(type) { const tabs = tabContextTabs.length ? tabContextTabs : getContextTabs(); if (!tabs.length) { return; } const result = tabs.map(tab => { const originalURL = getTabURL(tab); const title = getTabTitle(tab); const url = formatURL( originalURL, currentTabPopupWasRightClick ); switch (type) { case "url": return url; case "title": return title; case "both": if (url && title) { return `${url}#${title}`; } return url || title; default: return ""; } }) .filter(Boolean) .join("\n"); copyToClipboard(result); } // ========================================================================= // Tab context menu creation // ========================================================================= function createTabMenuItem(type) { const item = document.createXULElement("menuitem"); item.id = `${TAB_MENU_ID}-${type}`; item.setAttribute("label", tabLabels[type][0]); item.addEventListener("command", () => { copyTabs(type); }); return item; } function ensureTabMenuItems() { if (!tabPopup) { return; } let separator = document.getElementById( `${TAB_MENU_ID}-separator` ); if (!separator) { separator = document.createXULElement("menuseparator"); separator.id = `${TAB_MENU_ID}-separator`; } if (separator.parentNode !== tabPopup) { tabPopup.appendChild(separator); } for (const type of TAB_TYPES) { let item = document.getElementById( `${TAB_MENU_ID}-${type}` ); if (!item) { item = createTabMenuItem(type); } if (item.parentNode !== tabPopup) { tabPopup.appendChild(item); } } } // ========================================================================= // Tab context menu events // ========================================================================= function onTabPopupShowing() { const clickedTab = getContextTab(tabPopup); tabContextTabs = getContextTabs(tabPopup); const request = lastTabContextRequest; // Wayback is enabled ONLY when this exact tab's context menu // was opened through a physical right-click. currentTabPopupWasRightClick = !!( request && request.button === 2 && request.tab === clickedTab && Date.now() - request.timestamp < CONTEXT_REQUEST_TIMEOUT ); // Consume the request. lastTabContextRequest = null; const multiple = tabContextTabs.length > 1; // Update labels for multi-selection. for (const type of TAB_TYPES) { const item = document.getElementById( `${TAB_MENU_ID}-${type}` ); if (item) { item.setAttribute( "label", tabLabels[type][multiple ? 1 : 0] ); } } console.log( "[UCJS Copy Information] Tab context menu:", { tab: clickedTab?.label, multiple, openingButton: request?.button, wayback: currentTabPopupWasRightClick } ); } function onTabPopupHidden() { tabContextTabs = []; currentTabPopupWasRightClick = false; lastTabContextRequest = null; } // ========================================================================= // Places sidebar: History and Bookmarks // ========================================================================= function getPlacesTreeFromTarget(target) { try { let node = target; while (node) { if ( node.localName === "tree" || node.id === "placeContent" || node.id === "placesTree" ) { return node; } node = node.parentNode || node.host || null; } } catch (error) {} return null; } function getPlacesUtils() { try { if (typeof PlacesUtils !== "undefined") { return PlacesUtils; } if ( typeof ChromeUtils !== "undefined" && typeof ChromeUtils.import === "function" ) { try { const mod = ChromeUtils.import( "resource://gre/modules/PlacesUtils.jsm", {} ); if (mod?.PlacesUtils) { return mod.PlacesUtils; } } catch (error) {} } } catch (error) {} return null; } // ========================================================================= // Places information extraction // ========================================================================= function getSelectedInfo(ownerDoc) { try { if (!ownerDoc) { return { title: "", url: "" }; } const tree = ownerDoc.getElementById("placeContent") || ownerDoc.getElementById("placesTree") || ownerDoc.querySelector("tree") || ownerDoc.querySelector("[id*='places'] tree") || ownerDoc.getElementsByTagName("tree")[0] || null; if (!tree) { return { title: "", url: "" }; } let idx = -1; try { if ( typeof tree.currentIndex === "number" && tree.currentIndex >= 0 ) { idx = tree.currentIndex; } else if ( typeof tree.selectedIndex === "number" && tree.selectedIndex >= 0 ) { idx = tree.selectedIndex; } else if ( tree.view?.selection && typeof tree.view.selection.currentIndex === "number" ) { idx = tree.view.selection.currentIndex; } else if ( tree.view?.selection && typeof tree.view.selection.getRangeAt === "function" ) { try { idx = tree.view.selection.getRangeAt(0).start; } catch (error) {} } } catch (error) {} // Try the selected node directly. if (idx === -1 && tree.selectedNode) { const node = tree.selectedNode; const title = node.title || node.getAttribute?.("label") || node.getAttribute?.("title") || ""; const url = node.uri || node.href || node.getAttribute?.("uri") || node.getAttribute?.("url") || ""; if (title || url) { return { title, url }; } } if (idx === -1) { return { title: "", url: "" }; } // Prefer Firefox's native PlacesUtils helper. const PU = getPlacesUtils(); if ( PU && typeof PU.getURLAndTitleFromView === "function" && tree.view ) { try { const info = PU.getURLAndTitleFromView( tree.view, idx ); if (info && (info.url || info.title)) { return { title: info.title || "", url: info.url || "" }; } } catch (error) {} } // Fallback: inspect the selected row's columns. try { if ( tree.view && typeof tree.view.getCellText === "function" && tree.columns ) { let title = ""; let url = ""; const cols = tree.columns.childNodes; for (let i = 0; i < cols.length; i++) { const col = cols[i]; try { const cellText = tree.view.getCellText( idx, col ); if (!cellText) { continue; } if ( !url && /^[a-z][a-z0-9+.-]*:\/\//i.test(cellText) ) { url = cellText; } else if (!title) { title = cellText; } } catch (error) {} } if (title || url) { return { title, url }; } } } catch (error) {} // Fallback: obtain the node from the tree view. try { if ( tree.view && typeof tree.view.nodeForTreeIndex === "function" ) { const node = tree.view.nodeForTreeIndex(idx); if (node) { const title = node.title || node.label || node.name || ""; const url = node.uri || node.url || node.href || ""; if (title || url) { return { title, url }; } } } } catch (error) {} // Final fallback: inspect treechildren. try { const treechildren = tree.querySelector("treechildren"); if (treechildren) { const items = treechildren.childNodes; if (items && items.length > idx && idx >= 0) { const item = items[idx]; if (item) { const el = item.querySelector?.("treecell") || item; const title = el.getAttribute?.("label") || el.getAttribute?.("title") || el.textContent || ""; const url = el.getAttribute?.("uri") || el.getAttribute?.("url") || el.getAttribute?.("href") || ""; return { title, url }; } } } } catch (error) {} return { title: "", url: "" }; } catch (error) { Components.utils.reportError( "[UCJS Copy Information] Places extraction error: " + error ); return { title: "", url: "" }; } } // ========================================================================= // Places context menu creation // ========================================================================= function createPlacesMenuItems(popup) { try { if (!popup || !popup.ownerDocument) { return; } const ownerDoc = popup.ownerDocument; // Reuse existing items if the popup was opened before. const existingUrl = ownerDoc.getElementById( PLACES_MENU_IDS.url ); const existingTitle = ownerDoc.getElementById( PLACES_MENU_IDS.title ); const existingBoth = ownerDoc.getElementById( PLACES_MENU_IDS.both ); if ( existingUrl?.parentNode === popup && existingTitle?.parentNode === popup && existingBoth?.parentNode === popup ) { return; } function createMenuItem(type, accesskey, existing) { const item = existing || ( typeof ownerDoc.createXULElement === "function" ? ownerDoc.createXULElement("menuitem") : ownerDoc.createElement("menuitem") ); item.setAttribute("id", PLACES_MENU_IDS[type]); item.setAttribute("label", placesLabels[type]); item.setAttribute("accesskey", accesskey); item.setAttribute("crop", "end"); return item; } // Copy Page URL. const miUrl = createMenuItem( "url", "L", existingUrl ); miUrl.addEventListener("command", () => { const { url } = getSelectedInfo(ownerDoc); copyToClipboard( formatURL( url, currentPlacesPopupWasRightClick ) ); }); // Copy Page Title. const miTitle = createMenuItem( "title", "T", existingTitle ); miTitle.addEventListener("command", () => { const { title } = getSelectedInfo(ownerDoc); copyToClipboard(title); }); // Copy Page URL + Title. const miBoth = createMenuItem( "both", "U", existingBoth ); miBoth.addEventListener("command", () => { const { title, url } = getSelectedInfo(ownerDoc); const formattedURL = formatURL( url, currentPlacesPopupWasRightClick ); if (formattedURL && title) { copyToClipboard(`${formattedURL}#${title}`); } else { copyToClipboard(formattedURL || title); } }); // Insert after Firefox's built-in Copy item. const copyItem = popup.querySelector("#placesContext_copy"); if (copyItem && copyItem.parentNode === popup) { copyItem.insertAdjacentElement("afterend", miUrl); miUrl.insertAdjacentElement("afterend", miTitle); miTitle.insertAdjacentElement("afterend", miBoth); } else { if (miUrl.parentNode !== popup) { popup.appendChild(miUrl); } if (miTitle.parentNode !== popup) { popup.appendChild(miTitle); } if (miBoth.parentNode !== popup) { popup.appendChild(miBoth); } } } catch (error) { Components.utils.reportError( "[UCJS Copy Information] Places menu error: " + error ); } } // ========================================================================= // Mouse event tracking // ========================================================================= function onMouseDown(event) { const tab = getTabFromTarget(event.target); lastTabContextRequest = tab ? { tab, button: event.button, timestamp: Date.now() } : null; const tree = getPlacesTreeFromTarget(event.target); lastPlacesContextRequest = tree ? { button: event.button, tree, timestamp: Date.now() } : null; } // ========================================================================= // Context menu event tracking // ========================================================================= function onContextMenu(event) { // Tab context menu. // Record the opening button, including keyboard-triggered menus. const tab = getTabFromTarget(event.target); if (tab) { lastTabContextRequest = { tab, button: event.button, timestamp: Date.now() }; } else if ( !lastTabContextRequest || event.button !== 2 || lastTabContextRequest.button !== 2 || Date.now() - lastTabContextRequest.timestamp >= CONTEXT_REQUEST_TIMEOUT ) { lastTabContextRequest = null; } // History / Bookmarks sidebar. const tree = getPlacesTreeFromTarget(event.target); if (tree) { lastPlacesContextRequest = { button: event.button, tree, timestamp: Date.now() }; } else if ( !lastPlacesContextRequest || event.button !== 2 || lastPlacesContextRequest.button !== 2 || Date.now() - lastPlacesContextRequest.timestamp >= CONTEXT_REQUEST_TIMEOUT ) { lastPlacesContextRequest = null; } } // ========================================================================= // Places popup events // ========================================================================= function onPlacesPopupShowing(event) { const popup = event.target; if (!popup || popup.id !== "placesContext") { return; } const request = lastPlacesContextRequest; currentPlacesPopupWasRightClick = !!( request && request.button === 2 && Date.now() - request.timestamp < CONTEXT_REQUEST_TIMEOUT ); // Consume the request. lastPlacesContextRequest = null; console.log( "[UCJS Copy Information] Places context menu:", { openingButton: request?.button, wayback: currentPlacesPopupWasRightClick } ); createPlacesMenuItems(popup); } function onPlacesPopupHidden(event) { if (event.target?.id !== "placesContext") { return; } currentPlacesPopupWasRightClick = false; lastPlacesContextRequest = null; } // ========================================================================= // Cleanup // ========================================================================= function cleanup() { window.removeEventListener( "mousedown", onMouseDown, true ); window.removeEventListener( "contextmenu", onContextMenu, true ); window.removeEventListener( "popupshowing", onPlacesPopupShowing, true ); window.removeEventListener( "popuphidden", onPlacesPopupHidden, true ); window.removeEventListener( "unload", cleanup, false ); if (tabPopup) { tabPopup.removeEventListener( "popupshowing", onTabPopupShowing ); tabPopup.removeEventListener( "popuphidden", onTabPopupHidden ); } if (startupObserver) { try { Services.obs.removeObserver( startupObserver, "browser-delayed-startup-finished" ); } catch (error) {} startupObserver = null; } initialized = false; } // ========================================================================= // Initialization // ========================================================================= function start() { if (initialized) { return; } initialized = true; // Install global listeners for mouse tracking and Places menus. window.addEventListener( "mousedown", onMouseDown, true ); window.addEventListener( "contextmenu", onContextMenu, true ); window.addEventListener( "popupshowing", onPlacesPopupShowing, true ); window.addEventListener( "popuphidden", onPlacesPopupHidden, true ); window.addEventListener( "unload", cleanup, false ); // Firefox creates tabContextMenu during browser initialization. tabPopup = document.getElementById("tabContextMenu"); if (tabPopup) { ensureTabMenuItems(); tabPopup.addEventListener( "popupshowing", onTabPopupShowing ); tabPopup.addEventListener( "popuphidden", onTabPopupHidden ); console.log( "[UCJS Copy Information] Tab context menu initialized." ); } else { console.error( "[UCJS Copy Information] tabContextMenu not found." ); } console.log( "[UCJS Copy Information] Initialized." ); } // ========================================================================= // Browser startup // ========================================================================= if (window.gBrowserInit?.delayedStartupFinished) { start(); } else { startupObserver = (subject, topic) => { if (topic !== "browser-delayed-startup-finished") { return; } try { Services.obs.removeObserver( startupObserver, "browser-delayed-startup-finished" ); } catch (error) {} startupObserver = null; start(); }; Services.obs.addObserver( startupObserver, "browser-delayed-startup-finished" ); } })();