Skip to content

Instantly share code, notes, and snippets.

@dmertl
Last active May 12, 2024 09:59
Show Gist options
  • Save dmertl/69d901ce8437aa1afc7218e1164a6186 to your computer and use it in GitHub Desktop.
Save dmertl/69d901ce8437aa1afc7218e1164a6186 to your computer and use it in GitHub Desktop.
Tampermonkey Cheatsheet

Access Tab Data

// Get our tab object and save some data into it
GM_getTab(function(tab_self) {
    tab_self.created = Date.now();
    tab_self.location_href = window.location.href.toString();
    GM_saveTab(tab_self);
});
// Get our tab object and then compare it to all the other tab objects
// TODO: namespacing? or other tabs that aren't executed in our script.
// TODO: Better way to determine self vs. other tab?
// TODO: Better way for tab IDs?
GM_getTab(function(self_tab) {
    GM_getTabs(function(tabs) {
        for(const i in tabs) {
            let tab = tabs[i];
            if (tab.created === self_tab.created && tab.location_href === self_tab.location_href) {
                console.log('Tab ' + i + ' is us');
                continue;
            }
            if (tab.location_href === self_tab.location_href) {
                console.log('Tab ' + i + ' is on the same URL as us, they were created at ' + tab.created);
            }
        }
    });
});

Trigger Events Across Tabs

// If you want to trigger something from the tampermonkey menu, add a command to it
// Have it write a new value to trigger_event_here, current time is just convenient
GM_registerMenuCommand("Trigger Event", function(e) {
    GM_setValue('trigger_event_here', Date.now());
});

// Add a listener that watches for any change to the shared value trigger_event_here
GM_addValueChangeListener('trigger_event_here', function(key, oldValue, newValue, remote) {
    console.log('Event triggered by ' + (remote ? 'another tab ' + 'us'));
    // Do stuff
});

Communicate Across Tabs

// TODO: Same event idea, but can pass data as the event object or something

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment