Reputation: 39
I'm looking for a solution to load a function via href. href=javascript:myFunction()
doesn't work.
The reason why I can't use onClick or an eventListener is because I want the middle mouse button to open the link I would get from the function in a new tab.
I can't put the final link directly since I need to gather the link first, and I want to do that only when the href is used.
Is this possible?
PS: This is about a tamper-/Greasemonkey script
Upvotes: 2
Views: 3637
Reputation: 39
I found the solution, using GreaseMonkeys // @run-at document-start
function it is possible to actually execute GM BEFORE Page-load.
http://wiki.greasespot.net/Metadata_Block#.40run-at
Therefore I was able to define the function and replace the href easily.
Have a nice day
Upvotes: 0
Reputation: 4673
You can just store the function name in any attribute and then call it in the onclick handler.
E.g. if you want this to be done on middle click with jquery you can do it like this:
html:
<a id='link' href='func' >link</a>
js:
$("#link").on('click', function(e) {
if( e.which == 2 ) {
e.preventDefault();
if (typeof window[$(this).attr('href')] === "function")
window[$(this).attr('href')]();
}
});
function func(){
alert('func called');
}
In plain js with addEventListener you can check middle mouse via e.button
like this:
document.getElementById('link').addEventListener("click", function(e){
if(e.button == 1){
e.preventDefault();
if (typeof window[this.getAttribute("href")] === "function")
window[this.getAttribute("href")]();
}
});
Upvotes: 1
Reputation: 423
If you need after page load
HTML
<a href="javascript:hello('Hello');" >link</a>
JS
hello = function(value)
{
console.log(value)
}
Upvotes: 0
Reputation: 10874
Not sure why you can't get it to work, this works fine.
Just make sure your function is defined BEFORE the element. In your <head>
for example.
HTML
<a href="javascript:test();">Test</a>
JS
function test() {
alert("executed");
return false;
}
If you are limited to after dom ready with Greasemonkey here is a work around you could use. You still need to be able to define something before the elements but not the methods.
Basically if you create a name space prior the elements you can then add methods to that name space after the document is loaded and the element will still work.
HTML
<a href="javascript:test.foo();">Test</a>
JS
// jsfiddle load this in the head
var test = {};
// jquery used to run on dom ready
$(function() {
// add the method use by the element
test.foo = function() {
alert("executed");
return false;
}
});
Upvotes: 4