I have a Greasemonkey script that works fine in Firefox and Opera. However, I struggle to get it working in Chrome. The problem is entering a function on the page that may be called by code from the page. Here is what I am doing so far:
First, I get a reference link to unsafeWindow for Firefox. This allows me to have the same code for FF and Opera (and Chrome, I thought).
var uw = (this.unsafeWindow) ? this.unsafeWindow : window;
Then I add a function to the page. This is really a very thin shell that does nothing but call the corresponding function in the context of my GM script:
uw.setConfigOption = function(newValue) { setTimeout(setConfigOption, 0, newValue); }
Then in my script:
setConfigOption = function(newValue) {
Finally, I add HTML to the page with a link to call the function.
var p = document.createElement('p'); p.innerHTML = '<a href="javascript:setConfigOption(1)">set config option to 1</a>'; document.getElementById('injection-point').appendChild(p);
To summarize: In Firefox, when a user clicks on this nested link, he makes a function call on unsafeWindow, which then runs a timeout, which calls the corresponding function in the context of my GM script, which then performs the actual processing. (Correct me if I am wrong here.)
In Chrome, I just get the error "Uncaught ReferenceError: setConfigOption not defined". Indeed, entering "window.setConfigOption" into the console gives "undefined". Firebug and the Opera Developer Console have a feature.
Maybe there is another way to do this, but some of my functions call the Flash object on the page, which I believe requires me to have functions in the context of the page.
I quickly looked at the unsafeWindow alternatives on the Greasemonkey wiki, but they all look pretty ugly. Am I completely on the wrong track here, or do I need to study them more closely?
SOLUTION: I followed Max S. 'tips , and now it works in both Firefox and Chrome. Since the functions that I needed to access the page had to go into normal, I moved the entire script page to the page, i.e. It is completely wrapped in a function that he called "main ()".
To make the extra ugliness of this hack a little more bearable, I could at least refuse to use unsafeWindow and wrappedJSObject now.
I have not yet been able to get the content area runner from the wiki Greasemonkey. It should do the same and it seems to execute just fine, but my functions are never available for the <a> elements on the page, for example. I still do not understand why this is so.