Activate Google Translate instead of opening a new tab Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
asad41163
Posts: 268
Joined: 29 Jul 2014, 14:31

Activate Google Translate instead of opening a new tab

27 Jan 2020, 22:34

Welcome Everybody
The following code is from here: https://www.autohotkey.com/boards/viewtopic.php?f=76&t=71837&p=310921#top

Code: Select all

F2::
Send ^c
ClipWait, 1
Clipboard := RegExReplace(RegExReplace(Clipboard, " ","%20"),"`r`n","%0A")
Output := "https://translate.google.com?sl=en&tl=pt#view=home&op=translate&sl=auto&tl=en&text="   Clipboard
Run, firefox.exe %Output%
return
Written by creator Odlanir, The code copies the text, and opens a new tab for Google translation (translation from English to French), and pastes the text with it every time you press F2.
My question is:
What should be modified in the code in order to activate the already open tab from Google for translation instead of opening a new tab every time I press F2?
This is the image of the Active Window Info.
Active Window Info.PNG
Active Window Info.PNG (35.9 KiB) Viewed 3435 times
Please Help,
Thanks in advance
User avatar
boiler
Posts: 17404
Joined: 21 Dec 2014, 02:44

Re: Activate Google Translate instead of opening a new tab  Topic is solved

28 Jan 2020, 00:05

Try this:

Code: Select all

F2::
Send ^c
ClipWait, 1
Clipboard := "https://translate.google.com?sl=en&tl=pt#view=home&op=translate&sl=auto&tl=en&text="
	. RegExReplace(RegExReplace(Clipboard, " ","%20"),"`r`n","%0A")
if !WinExist("ahk_class MozillaWindowClass ahk_exe firefox.exe")
{
	Run, firefox.exe
	Sleep, 500
}
WinActivate, ahk_class MozillaWindowClass ahk_exe firefox.exe
WinWaitActive, ahk_class MozillaWindowClass ahk_exe firefox.exe
Send, !d^v{Enter}
return
asad41163
Posts: 268
Joined: 29 Jul 2014, 14:31

Re: Activate Google Translate instead of opening a new tab

28 Jan 2020, 14:10

The wonderful professor: boiler

you made my work very easy.
Accurate and distinguished work .. Thank you very much
garry
Posts: 3795
Joined: 22 Dec 2013, 12:50

Re: Activate Google Translate instead of opening a new tab

28 Jan 2020, 14:53

thank you boiler
google translator scripts from users 'teadrinker' and 'Osprey'
https://www.autohotkey.com/boards/viewtopic.php?p=273621#p273621
example, teadrinker's translator , a GUI added

EDIT : small modified

Code: Select all

;- translator from user teadrinker / with GUI 
/*
modified=20200131 maybe #warn can be desactivated , sometimes error but script runs
modified=20200130  translate clipboard again in other language with dropdownlist (ddl1)
modified=20200129  warn / translate when language change (ddl1) 
modified=20191019  ( teadrinker ) edited 1 time in total. 
modified=20190422  EDIT CreateScriptObj() ( teadrinker )
created =20190419
select language , copy marked text ctrl+c > see translation in selected language
*/
;-------------------------------------------------------------------------------
#NoEnv
;#Warn  ;- can desactivate it / sometimes error but script runs
;SendMode Input
setworkingdir,%a_scriptdir%
tl1:=""

Gui,1:default
Gui,1: +AlwaysOnTop  
Gui,1: -DPIScale
SS_REALSIZECONTROL := 0x40
wa:=a_screenwidth
ha:=a_screenheight
xx:=100
clipboard=
cl=
ex:=""
transform,s,chr,32
gosub,language
rssini=%a_scriptdir%\translate.ini
ifnotexist,%rssini%    ;- first run
    {
    translateto=pt     ;- portuguese
    IniWrite,%translateto%, %rssini% ,Lang1  ,key1
    }
Gui,1:Color,Black,Black
Gui, Font,s12 cYellow ,Lucida Console 
IniRead, tl1, %rssini%,Lang1 ,key1
global tl1,js

Gui,add,dropdownlist, x10 y10 w320 vDDL1 gddl2 ,%e5x%

W :=(wa*29)/xx , H :=(ha*89)/xx , y:=(ha*2)/xx
;Gui,add,edit,x1 y%y%  w%w% h%h% vED1  -vscroll -border -E0x200,
Gui,add,edit,x1 y50  w%w% h%h% vED1 readonly -border -E0x200,
;Gui,add,text,x0 y0 w0 vT1 ,
W :=(wa*30)/xx , H :=(ha*92)/xx  , x:=(wa-w)
Gui, Show,x%x% y1 w%w% h%h% ,TRANSLATE
GuiControl,1:Choose,ddl1,%tl1%
GuiControl, Focus,ED1
WinID := WinExist("A")
WinSetTitle, ahk_id %WinID%,, TRANSLATE_to_%tl1%
E0x200 = WS_EX_CLIENTEDGE
RETURN
;--------------------------
esc::exitapp
;--------------------------
Guiclose:
cl=
clipboard=
exitapp


/*
;------- Hotkey alt+F7 -------------------
!F7::
  send, ^c
  sleep,500
  clipwait,
  Gui, Show,
  GuiControl, Focus,ED1
 if (!ErrorLevel)
  {
  cl:=clipboard
  aa:=GoogleTranslate(cl)
  ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
  aa=
  ;cl=
  ;clipboard=
  GuiControl, Focus,ED1
  }
return
;--------------------------
*/

;-------------- OR : ------
;/*
;----- ( Hotkey) CTRL+C Clipboardchange ---------------------
OnClipboardChange:
If (A_EventInfo=1)
 {
 Gui, Show,
 GuiControl, Focus,ED1
 ClipWait,
 if (!ErrorLevel)
  {
  cl:=clipboard
  aa:=GoogleTranslate(cl)
  ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
  aa=
  ;cl=
  ;clipboard=
  GuiControl, Focus,ED1
  }
 }
return
;--------------------------
;*/


;--------------------------
ddl2:
Gui,1:submit,nohide
h1:=""
h2:=""
if DDL1<>
{
StringSplit,h,ddl1,`_
if h1<>
  {
  IniWrite,%h1%, %rssini% ,Lang1  ,key1
  tl1:=h1
  WinSetTitle, ahk_id %WinID%,, TRANSLATE_to_%h2%
  gosub,translateddlchange
  }
}
return
;----------------------------------------

;------- translate changed language -----
translateddlchange:
Guicontrolget,ed1
if ed1<>
{
aa:=GoogleTranslate(cl)      ;- translate clipboard again in other language
ControlSetText,edit1,%aa%, ahk_class AutoHotkeyGUI
aa=
}
return
;---------------------------------------


;;-------- https://www.autohotkey.com/boards/viewtopic.php?p=273621#p273621 ---
;- Last edited by teadrinker on Sat Oct 19, 2019 9:58 pm, edited 1 time in total. 
;MsgBox, % GoogleTranslate("今日の天気はとても良いです")
;MsgBox, % GoogleTranslate("Hello, World!", "en", "ru")
GoogleTranslate(str, from := "auto", to := "en")  {
   JS:=""
   trans:=""
   json:=""
   static JS := CreateScriptObj(), _ := JS.( GetJScript() ) := JS.("delete ActiveXObject;delete GetObject;")
   json := SendRequest(JS, str, to, from, proxy := "")
   oJSON := JS.("(" . json . ")")
   if !IsObject(oJSON[1])  {
      Loop % oJSON[0].length
         trans .= oJSON[0][A_Index - 1][0]
   }
   else  {
      MainTransText := oJSON[0][0][0]
      Loop % oJSON[1].length  {
         trans .= "`n+"
         obj := oJSON[1][A_Index-1][1]
         Loop % obj.length  {
            txt := obj[A_Index - 1]
            trans .= (MainTransText = txt ? "" : "`n" txt)
         }
      }
   }
   if !IsObject(oJSON[1])
      MainTransText := trans := Trim(trans, ",+`n ")
   else
      trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ")
   from := oJSON[2]
   trans := Trim(trans, ",+`n ")
   Return trans
}

SendRequest(JS, str, tl, sl, proxy) {
   ComObjError(false)
   http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
   ( proxy && http.SetProxy(2, proxy) )
   tl1=%tl1%
   ;http.open( "POST", "https://translate.google.com/translate_a/single?client=t&sl="
   ;                   "https://translate.google.com/#view=home&op=translate&client=t&sl="  ;- usual in web
   http.open( "POST", "https://translate.google.com/translate_a/single?client=webapp&sl="
      . sl . "&tl=" . tl1 . "&hl=" . tl1
      . "&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=0&ssel=0&tsel=0&pc=1&kc=1"
      . "&tk=" . JS.("tk").(str), 1 )
   http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
   http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
   http.send("q=" . URIEncode(str))
   http.WaitForResponse(-1)
   Return http.responsetext
}
URIEncode(str, encoding := "UTF-8")  {
   urlstr:=""-
   VarSetCapacity(var, StrPut(str, encoding))
   StrPut(str, &var, encoding)
   While code := NumGet(Var, A_Index - 1, "UChar")  {
      bool := (code > 0x7F || code < 0x30 || code = 0x3D)
      UrlStr .= bool ? "%" . Format("{:02X}", code) : Chr(code)
   }
   Return UrlStr
}
GetJScript()
{
   script =
   (
      var TKK = ((function() {
        var a = 561666268;
        var b = 1526272306;
        return 406398 + '.' + (a + b);
      })());
      function b(a, b) {
        for (var d = 0; d < b.length - 2; d += 3) {
            var c = b.charAt(d + 2),
                c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
                c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
            a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
        }
        return a
      }
      function tk(a) {
          for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
              var c = a.charCodeAt(f);
              128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ?
              (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240,
              g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
          }
          a = h;
          for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
          a = b(a, "+-3^+b+-f");
          a ^= Number(e[1]) || 0;
          0 > a && (a = (a & 2147483647) + 2147483648);
          a `%= 1E6;
          return a.toString() + "." + (a ^ h)
      }
   )
   Return script
}
CreateScriptObj() {
   static doc
   doc := ComObjCreate("htmlfile")
   doc.write("<meta http-equiv='X-UA-Compatible' content='IE=9'>")
   Return ObjBindMethod(doc.parentWindow, "eval")
}
;-----------------------------------------------------------------

;-- some examples to select 
language:
e5x:=""
e5x=
(Ltrim join|
nl_Nederlands
af_Suid-Afrika
fy_Fryslân
eu_Basque
ca_Catalan
de_Deutsch
da_Dansk
sv_Sverige
no_Norge
is_Iceland
fi_Suomen
en_English
pt_Portugues
es_Español
it_Italia
fr_Français
ru_Rossija
zh-CN_Chinese
ja_Nippon
ko_Korea
ro_Romania
bg_Bulgaria
mk_Macedonia
el_Greek
tr_Turkiye
sq_Albania
hr_Croatia
sr_Serbia
sl_Slovenia
hu_Hungary
cs_Czech
sk_Slovakia
pl_Poland
be_Belarus
uk_Ukraina
et_Estonia
lv_Latvija
lt_Lituania
az_Azerbaijan 
ka_Georgian
ar_Arabic
iw_Hebrew
hi_Hindi
id_Indonesia
ms_Malaysia
vi_Vietnam
th_Thai
ta_Tamil
ur_Urdu
sw_Swahili
bn_Bengal
%s%
)
return
;====================== END SCRIPT ==================================================

Last edited by garry on 31 Jan 2020, 04:24, edited 3 times in total.
asad41163
Posts: 268
Joined: 29 Jul 2014, 14:31

Re: Activate Google Translate instead of opening a new tab

28 Jan 2020, 22:50

Welcome Everybody
Hi, garry:

I didn't know how to use it
I tried and it gave me this message.
Msg.PNG
Msg.PNG (20.04 KiB) Viewed 3289 times
I didn't know the hotkey, please tell me how it works.
thanks in advance.
garry
Posts: 3795
Joined: 22 Dec 2013, 12:50

Re: Activate Google Translate instead of opening a new tab

29 Jan 2020, 01:23

start script, mark text and use ctrl+c > translate to selected language ( keeps last selected language in translate.ini file )
be sure script copy is correct , otherwise ask user 'teadrinker'
example : translated to german
Image
garry
Posts: 3795
Joined: 22 Dec 2013, 12:50

Re: Activate Google Translate instead of opening a new tab

29 Jan 2020, 13:39

don't know , why you have error
made small modification, can use #warn command
as hotkey can also try alt+F7 ( at the moment ctrl+c ( onclipboardchange ) is activated )
User avatar
boiler
Posts: 17404
Joined: 21 Dec 2014, 02:44

Re: Activate Google Translate instead of opening a new tab

29 Jan 2020, 13:49

Perhaps you are using a very old version of AHK. You might try upgrading to the latest version (1.1.32). What do you get when your run this:

Code: Select all

MsgBox, % A_AhkVersion
asad41163
Posts: 268
Joined: 29 Jul 2014, 14:31

Re: Activate Google Translate instead of opening a new tab

30 Jan 2020, 20:22

Excuse me please:
Where is [#warn] command on the keyboard?
--------

I am using windows 7, and AHK Version is: 1.1.30.03


  I apologize because my English is not good.
garry
Posts: 3795
Joined: 22 Dec 2013, 12:50

Re: Activate Google Translate instead of opening a new tab

31 Jan 2020, 03:49

#warn has nothing to do with key / keyboard , it's an ahk-command
it's possible to desactivate it , script shows also an error if you use wrong commands
see help file for #warn "C:\Program Files\AutoHotkey\AutoHotkey.chm"
;#warn ;- warn desactivated ( not used )
#Warn [WarningType, WarningMode]
Enables or disables warnings for specific conditions which may indicate an error, such as a typo or missing "global" declaration.
asad41163
Posts: 268
Joined: 29 Jul 2014, 14:31

Re: Activate Google Translate instead of opening a new tab

03 Feb 2020, 13:42

Hello, dear colleagues
Thank you very much, Mr. garry for the guidance and explanation
I really need a lot of study and research.
Thank you and thanks for Mr. boiler for your efforts.
wetware05
Posts: 750
Joined: 04 Dec 2020, 16:09

Re: Activate Google Translate instead of opening a new tab

09 Dec 2020, 11:10

How to reduce the script so that it only copies the translation to the clipboard? My argument: there are many utilities to translate, more flexible and with more options than this script, but I only need that when copying something to the clipboard it translates it, and copies the translation to the clipboard, and then I have the option to paste it or see how is the translation.

I have tried to follow the sequence of the script, but since a part is in java, there I already get lost. :cry: I am not able to remove the interface and just keep the copy and the translation. I catch that the variable aa is the one that is carrying the text on the clipboard.
garry
Posts: 3795
Joined: 22 Dec 2013, 12:50

Re: Activate Google Translate instead of opening a new tab

09 Dec 2020, 14:46

example , use a hotkey , here alt+h , and see translation in clipboard

Code: Select all

;-------- saved at 星期三 十二月 2020-12-09  19:27 UTC --------------
;- Activate Google Translate instead of opening a new tab 
;- https://www.autohotkey.com/boards/viewtopic.php?f=76&t=71993
;- translator from user teadrinker 
;- use HOTKEY = alt+h 

#persistent
tl1=pt                      ;-- <<< here define language ( example português )
global tl1,js
;------- Hotkey alt+h -------------------
!h::
  send, ^c
  sleep,500
  clipwait,2,1
 if (!ErrorLevel)
  {
  aa:=GoogleTranslate(clipboard)
  clipboard=%aa%
  aa=
  msgbox,%clipboard%
  }
clipboard=
return
;------------------
esc::exitapp
;---------------------------------------
;;-------- https://www.autohotkey.com/boards/viewtopic.php?p=273621#p273621 ---
;- Last edited by teadrinker on Sat Oct 19, 2019 9:58 pm, edited 1 time in total. 
;MsgBox, % GoogleTranslate("今日の天気はとても良いです")
;MsgBox, % GoogleTranslate("Hello, World!", "en", "ru")
GoogleTranslate(str, from := "auto", to := "en")  {
   JS:=""
   trans:=""
   json:=""
   static JS := CreateScriptObj(), _ := JS.( GetJScript() ) := JS.("delete ActiveXObject;delete GetObject;")
   json := SendRequest(JS, str, to, from, proxy := "")
   oJSON := JS.("(" . json . ")")
   if !IsObject(oJSON[1])  {
      Loop % oJSON[0].length
         trans .= oJSON[0][A_Index - 1][0]
   }
   else  {
      MainTransText := oJSON[0][0][0]
      Loop % oJSON[1].length  {
         trans .= "`n+"
         obj := oJSON[1][A_Index-1][1]
         Loop % obj.length  {
            txt := obj[A_Index - 1]
            trans .= (MainTransText = txt ? "" : "`n" txt)
         }
      }
   }
   if !IsObject(oJSON[1])
      MainTransText := trans := Trim(trans, ",+`n ")
   else
      trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ")
   from := oJSON[2]
   trans := Trim(trans, ",+`n ")
   Return trans
}
SendRequest(JS, str, tl, sl, proxy) {
   ComObjError(false)
   http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
   ( proxy && http.SetProxy(2, proxy) )
   tl1=%tl1%
   ;http.open( "POST", "https://translate.google.com/translate_a/single?client=t&sl="
   ;                   "https://translate.google.com/#view=home&op=translate&client=t&sl="  ;- usual in web
   http.open( "POST", "https://translate.google.com/translate_a/single?client=webapp&sl="
      . sl . "&tl=" . tl1 . "&hl=" . tl1
      . "&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=0&ssel=0&tsel=0&pc=1&kc=1"
      . "&tk=" . JS.("tk").(str), 1 )
   http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
   http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
   http.send("q=" . URIEncode(str))
   http.WaitForResponse(-1)
   Return http.responsetext
}
URIEncode(str, encoding := "UTF-8")  {
   urlstr:=""-
   VarSetCapacity(var, StrPut(str, encoding))
   StrPut(str, &var, encoding)
   While code := NumGet(Var, A_Index - 1, "UChar")  {
      bool := (code > 0x7F || code < 0x30 || code = 0x3D)
      UrlStr .= bool ? "%" . Format("{:02X}", code) : Chr(code)
   }
   Return UrlStr
}
GetJScript()
{
   script =
   (
      var TKK = ((function() {
        var a = 561666268;
        var b = 1526272306;
        return 406398 + '.' + (a + b);
      })());
      function b(a, b) {
        for (var d = 0; d < b.length - 2; d += 3) {
            var c = b.charAt(d + 2),
                c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
                c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
            a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
        }
        return a
      }
      function tk(a) {
          for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
              var c = a.charCodeAt(f);
              128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ?
              (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240,
              g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
          }
          a = h;
          for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
          a = b(a, "+-3^+b+-f");
          a ^= Number(e[1]) || 0;
          0 > a && (a = (a & 2147483647) + 2147483648);
          a `%= 1E6;
          return a.toString() + "." + (a ^ h)
      }
   )
   Return script
}
CreateScriptObj() {
   static doc
   doc := ComObjCreate("htmlfile")
   doc.write("<meta http-equiv='X-UA-Compatible' content='IE=9'>")
   Return ObjBindMethod(doc.parentWindow, "eval")
}
;========================== END SCRIPT ===========================

wetware05
Posts: 750
Joined: 04 Dec 2020, 16:09

Re: Activate Google Translate instead of opening a new tab

09 Dec 2020, 15:59

Hey!!!, garry, it works perfectly.

many thanks :bravo: :dance: :superhappy:

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Bing [Bot], Marium0505 and 331 guests