8

I have written a userscript that I would like to run when I call it (not every time a matching web page loads). Ideally I'd like to create a toolbar button for starting this script. How can this be done?

PS: I need it to run in the same context with the web page scripts and be able to call functions embedded in it.

Ivan
  • 63,011
  • 101
  • 250
  • 382
  • 1
    I don't know why the downvotes, but I highly suspect it can't be done. You will need to write your own extension - and it's quite possible to reach the page's context. – Xan Sep 09 '14 at 18:36
  • "Why downvotes": the accepted answer starts with *"I don't know exactly what toolbar you're talking about"*.... IMO, just a bit of sample code or a screenshot would have prevented that. That said, I learned something new with derjanb's answer, so thanks for that! – brasofilo Nov 21 '17 at 01:03

1 Answers1

16

I don't know exactly what toolbar you're talking about, but it's possible to add a menu command to Tampermonkey's action menu.

Since your script should be able to run at any page you need to @include all pages what might slow down pages with a lot of iframes a little bit.

This script will execute the main function (with the alert statement) only if the menu command was clicked.

// ==UserScript==
// @name       Run only on click
// @namespace  http://tampermonkey.net/
// @version    0.1
// @description  Run only on click
// @include    /https?:\/\/*/
// @copyright  2012+, You
// @grant      unsafeWindow
// @grant      GM_registerMenuCommand
// ==/UserScript==

GM_registerMenuCommand('Run this now', function() { 
    alert("Put script's main function here");
}, 'r');

Accessing the pages functions is possible by two ways:

function main () {
  window.function_at_the_page();
}

var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ main +')();'));
(document.body || document.head || document.documentElement).appendChild(script);

or just:

unsafeWindow.function_at_the_page();
derjanb
  • 1,020
  • 10
  • 13