Inject Google Translate Widget

Userscript version of "Google Translate This" from https://github.com/andreicristianpetcu/google_translate_this. v0.1 2019-11-03

As of 2019-11-03 21:19:55 UTC. See the latest version.

// ==UserScript==
// @name        Inject Google Translate Widget
// @description Userscript version of "Google Translate This" from https://github.com/andreicristianpetcu/google_translate_this. v0.1 2019-11-03
// @author      Jefferson "jscher2000" Scher
// @namespace   JeffersonScher
// @version     0.1
// @copyright   Copyright 2019 Jefferson Scher. Mostly Copyright 2019 Andrei Cristian Petcu.
// @license     GPL-3.0
// @match       http*://*/*
// @grant       GM_registerMenuCommand
// ==/UserScript==

function injectGoogleTranslateWidget(){
  // From: https://github.com/andreicristianpetcu/google_translate_this/blob/master/scripts/inject_google_translate_content.js as of Sept. 8, 2019 (last line omitted)
  var gtdiv = document.createElement("div");
  gtdiv.setAttribute("id", "google_translate_element");
  gtdiv.style.display="none";
  document.body.appendChild(gtdiv);

  var googleTranslateElementInitCode = "function(){ \
    new google.translate.TranslateElement({pageLanguage: 'auto', autoDisplay: true}, 'google_translate_element'); \
    setTimeout(function(){ \
      var iframe = document.getElementsByClassName('goog-te-banner-frame')[0]; \
      var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; \
      iframeDocument.getElementsByClassName('goog-te-button')[0].children[0].children[0].click(); \
    }, 1000); \
  }";

  var globalFunctionScript = document.createElement('script');
  globalFunctionScript.text = "googleTranslateElementInit = " + googleTranslateElementInitCode;
  globalFunctionScript.type = "text/javascript";
  document.getElementsByTagName('head')[0].appendChild(globalFunctionScript);

  var bg_script = document.createElement('script');
  bg_script.type = "text/javascript";
  bg_script.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
  document.getElementsByTagName('head')[0].appendChild(bg_script);
}  

// This should work in Violentmonkey and Tampermonkey, but not Greasemonkey.
try {
  GM_registerMenuCommand("Inject Google Translate Widget", injectGoogleTranslateWidget);
} catch (err) {
  console.log('Error adding Inject Google Translate Widget menu item: ' + err.message);
}