Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a toolbar button for a Chrome Tampermonkey user script?

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.

like image 760
Ivan Avatar asked Sep 09 '14 16:09

Ivan


1 Answers

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();
like image 89
derjanb Avatar answered Oct 25 '22 01:10

derjanb