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.

2
  • 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. Commented Sep 9, 2014 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! Commented Nov 21, 2017 at 1:03

1 Answer 1

17

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.