Search code examples
javascriptcross-browsergoogle-chromegreasemonkeyuserscripts

Help making userscript work in chrome


I've written a userscript for Gmail : Pimp.my.Gmail & i'd like it to be compatible with Google Chrome too.
Now i have tried a couple of things, to the best of my Javascript knowledge (which is very weak) & have been successful up-to a certain extent, though im not sure if it's the right way.

Here's what i tried, to make it work in Chrome:
The very first thing i found is that contentWindow.document doesn't work in chrome, so i tried contentDocument, which works.
BUT i noticed one thing, checking the console messages in Firefox and Chrome, i saw that the script gets executed multiple times in Firefox whereas in Chrome it just executes once!
So i had to abandon the window.addEventListener('load', init, false); line and replace it with window.setTimeout(init, 5000); and i'm not sure if this is a good idea.

The other thing i tried is keeping the window.addEventListener('load', init, false); line and using window.setTimeout(init, 1000); inside init() in case the canvasframe is not found.

So please do lemme know what would be the best way to make this script cross-browser compatible. Oh and im all ears for making this script better/efficient code wise (which im sure is possible)

edit: no help...? :'(

edit 28-Apr:
i re-wrote the code a little and now it looks something like this.:

if(document.location != top.location) return;

(function() {
var interval = window.setInterval(waitforiframe, 3000);
var canvas;
function waitforiframe() {
    console.log("Finding canvas frame");
    canvas = document.getElementById("canvas_frame");
    if (canvas && canvas.contentDocument) {
        console.log("Found canvas frame");
        pimpmygmail();
    }
}
function pimpmygmail() {
    gmail = canvas.contentDocument;
    if(!gmail) return;
    window.clearInterval(interval);
    console.log("Lets PIMP.MY.GMAIL!!!");
    ......rest of the code......
})();

This works perfectly fine in Firefox, but in Chrome, it gives me a top is undefined error. Another thing i noticed is that if i remove the first line if(document.location != top.location) return; , the waitforiframe() method keeps getting called over and over again. (ie i see the "Finding canvas frame" error in the console)

can someone tell me what does the first line do? i mean what does it achieve & why does the waitforiframe() method run forever if i remove that line??


Solution

  • A BIG THANK YOU TO ALL WHO HELPED! -_- meh

    btw, this was all i needed at the beginning of the script:

    try { if(top.location.href != window.location.href) { return; } }
    catch(e) { return; }