Search code examples
javascriptgreasemonkeyuserscripts

Using google translate api in userscript


I am making a userscript for facebook that would help translate text using Google Translate Api. Script is injecting html and css content successfully into facebook.

Problem is with Google Translate Api. I am injecting a script tag

var s = document.createElement('script');
s.type="text/javascript";
s.src='https://www.google.com/jsapi?key=AIzaSyD24A-czAdTj8pPc5ugo0bYiPRx8Rc2pXo';
document.body.appendChild(s);

First this script is loading the url 2 or 3 times.

To actually use the Language Api I am injecting another script tag

var ldfun = document.createElement('script');
ldfun.setAttribute('type', 'application/javascript');
ldfun.textContent= "google.load('language','1');";
document.body.appendChild(ldfun);

this script is not running and sometimes it runs then the page naviages away.

Help please


Solution

  • Make sure the script is not running in iFrames and then use a delay to ensure the library JS is loaded (Otherwise, the browser will run those 2 scripts asynchronously.)

    Something like this:

    if (window.top != window.self)  //-- Don't run on frames or iframes
        return;
    
    function addJS_Node (text, s_URL)
    {
        var scriptNode                      = document.createElement ('script');
        scriptNode.type                     = "text/javascript";
    
        if (text)  scriptNode.textContent   = text;
        if (s_URL) scriptNode.src           = s_URL;
    
        //--- document.head is best.  Use document.body only on poor target pages.
        document.head.appendChild (scriptNode);
    }
    
    //--- Load Google-Translate, JS API.
    addJS_Node (null, 'https://www.google.com/jsapi?key=AIzaSyD24A-czAdTj8pPc5ugo0bYiPRx8Rc2pXo');
    
    //--- Initialize Google-Translate after a delay to make sure it has loaded.
    setTimeout (function() {
        addJS_Node ("google.load('language','1');", null);
        },
        1500
    );