简体   繁体   中英

How to call a Greasemonkey function when a JavaScript link is clicked

So I recently started working on Greasemonkey scripts without much prior experience in JavaScript. It was going fine until I hit this roadbloack.

I'm writing a script for a page that has a small table of information. If a link at the bottom is clicked, the table expands fully in the page to display all information. I need to call a function in Greasemonkey when this happens, however, the link doesn't appear to have an ID or anything I can actually reference to watch it. It's simply this:

<a href="javascript: expandFullTable(false);"></a>

When it's clicked, the table expands and it then shows as true. I initially used the following to expand the table upon loading the page, but that broke several things:

window.location.href = ('javascript: expandFullTable(false)');

I've attempted using "click", "onclick", and even "mouseover" to have Greasemonkey detect when it's pressed but nothing seems to work. From what I can tell it's simply a link that calls a function, but after some significant searching I wasn't able to find out anything about how to reference it in my script. I'm sure it's incredibly simple, but it's frustrated me to no end.

You can hijack the function like this:

var oldExpandFullTable = unsafeWindow.expandFullTable;
unsafeWindow.expandFullTable = function() {
    // Do something
    alert("You clicked on that thing!");

    // Call the original function
    oldExpandFullTable.apply(this, arguments);
};

But since you tagged this this should let you retrieve the link:

var link = $("a[href^=\"javascript: expandFullTable\"]);

It should work if jQuery is injected into your script with @require . If it's already in the page, you can add this before to access it: var $ = unsafeWindow.jQuery; .

And by the way, perhaps you should learn more about unsafeWindow to avoid security holes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM