I need a javascript function to load first before calling it with GreaseMonkey. but it seems that GreaseMonkey always puts my code in the head of the html. How can I insert my code in the body instead. Preferably at the very end
2 Answers
To answer directly here:
var newElem = document.createElement( 'script'); //create a script tag
newElem.type = 'text/javascript'; // add type attribute
newElem.innerHTML = 'function myFunc() { alert( "alerting"); } myFunc();'; // add content i.e. function definition and a call
document.body.appendChild( newElem); // Insert it as the last child of body
That is the formal way but a shortest could be
document.body.appendChild( document.createElement( 'script'));
document.body.lastChild.innerHTML = 'function myFunc() { alert( "the alert"); } myFunc();'; // add content i.e. function definition and a make a call
But, your question description is confusing, you want to insert a Function to a page and then call it with GM? Why would insert it to the page then? Note that in the code above the call is within the page scope, not from GM, in this case you can't call it from GM, well... you would have to use unsafe but as usual not recommended, to call it you would have to insert nodes in the page something like:
someplace.innerHTML = '<a onclick=myFunc()>Execute myFunc</a>';
This function you want to insert does it need to be in page scope? You won't be able to call it from GM scope, if not just leave the function in the GM scope and call it, no insertion.
Comments
You can define a function, and then write it directly to a script element in the end of the body. E.g.:
function myFunc() {
// ...
}
document.body.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "(" + myFunc.toString() + ")();";
document.body.appendChild(script);
}, false);