Есть ли способ программно войти в Google Chrome?
Мне нужно войти в Google Chrome в домен приложений Google на большом количестве компьютеров. Каждый компьютер имеет доступ к своему имени пользователя, а также к временному паролю. Есть ли способ войти в Chrome автоматически? Было бы предпочтительнее сделать это без установки дополнительного программного обеспечения.
До сих пор я пытался войти в систему, используя скрипт Visual Basic SendKeys
метод для имитации нажатия клавиш. Хотя этот метод работает, он часто выходит из строя при обновлении Chrome, когда компьютер работает медленно или во время большинства других непредвиденных обстоятельств.
1 ответ
Это скорее временная мера, чем решение, поэтому я не собираюсь отмечать это как решение.
В настоящее время я решаю эту проблему, заставив программу сгенерировать и запустить файл VBS для ввода имени пользователя и пароля пользователя. Затем у меня есть другая программа, которая проверяет файл настроек Chrome, чтобы увидеть, был ли он успешно настроен. Если этого не произошло, скрипт запускается заново.
chromeConf.vbs (я написал другую программу, автоматически сгенерировавшую этот файл и запускающую его на каждом компьютере):
Set oShell = CreateObject("WScript.Shell")
oShell.SendKeys "^{ESCAPE}" 'start menue
WScript.Sleep 1000 'wait for it to load
oShell.SendKeys "chrome.exe" 'chrome
WScript.Sleep 1000
oShell.SendKeys "{ENTER}"
return = oShell.Run("waitForFocus.exe Chrome", 0, true)'wait for Chrome to open
oShell.SendKeys "%{F4}" 'go! be gone!
'Chrome has to be started twice to ensure the same start state on all computers
oShell.SendKeys "^{ESCAPE}" 'start menue
WScript.Sleep 1000 'wait for it to load
oShell.SendKeys "chrome.exe" 'chrome
WScript.Sleep 1000
oShell.SendKeys "{ENTER}"
return = oShell.Run("waitForFocus.exe Chrome", 0, true)
oShell.SendKeys "chrome://settings" 'settings
oShell.SendKeys "{ENTER}"
WScript.Sleep 5000
oShell.SendKeys "{TAB}{TAB}" 'select log in
oShell.SendKeys "{ENTER}"
WScript.Sleep 8000
oShell.SendKeys "{TAB}{TAB}" 'log in
oShell.SendKeys "user@example.com"
oShell.SendKeys "{TAB}"
oShell.SendKeys "{ENTER}"
WScript.Sleep 4000
oShell.SendKeys "password"
oShell.SendKeys "{TAB}"
oShell.SendKeys "{ENTER}"
WScript.Sleep 4000
oShell.SendKeys "{TAB}" 'link data
oShell.SendKeys "{TAB}"
oShell.SendKeys "{TAB}"
oShell.SendKeys "{TAB}"
oShell.SendKeys "{ENTER}"
WScript.Sleep 4000
oShell.SendKeys "{ESCAPE}" 'get rid of pesky user dialog
oShell.SendKeys "%{F4}" 'go! be gone!
источник waitForFocus.exe:
// waitForFocus.cpp : This program waits for a window of a specified name to load
//
#include "stdafx.h"
#include <string.h>
#include <atlstr.h>
#include <iostream>
using namespace std;
LPWSTR pszMem;
BOOL CALLBACK FindWindowBySubstr(HWND hwnd, LPARAM substring)
{
const DWORD TITLE_SIZE = 1024;
TCHAR windowTitle[TITLE_SIZE];
if (GetWindowText(hwnd, windowTitle, TITLE_SIZE))
{
string fstr = CW2A(windowTitle);//convert window title to string
if (fstr.find(LPCSTR(substring)) != string::npos && !(fstr.find("waitForFocus.exe") != string::npos)) { //is it what we want
cout << "Found window!" << endl;
_tprintf(TEXT("%s\n"), windowTitle);
SwitchToThisWindow(hwnd, true);//The true enables alt tab emulation which prevents the transparent window bug
return false;
}
}
return true;
}
int main(int argc, char* argv[])
{
if (argc > 2) {
cout << "This program takes 1 argument" << endl;
cout << "The argument should be part of the name of the window you want to wait for" << endl;
}
else if (argc == 2) {
if (string(argv[1]) == "/h" || string(argv[1]) == "-h" || string(argv[1]) == "/?" || string(argv[1]) == "-?"){
cout << "This program takes one input, part of the window name, and waits for that window to load" << endl;
}
else {
bool nfound = true;
while (nfound) {
HWND windowHandle = FindWindowA(0, argv[1]); //check if there is a window exactly matching what we want
if (windowHandle == NULL) {//no
HWND WINAPI GetForegroundWindow(void);//is the window already up (If so I dont have to look for it)
pszMem = (LPWSTR)VirtualAlloc((LPVOID)NULL,
(DWORD)(80), MEM_COMMIT,
PAGE_READWRITE);
GetWindowText(GetForegroundWindow(), pszMem,
80);
cout << GetForegroundWindow() << ", ";
string resstr = CW2A(pszMem);
wcout << pszMem << endl;
if (resstr.find(string(argv[1])) != string::npos && !(resstr.find(string("waitForFocus.exe")) != string::npos)) {
cout << "found!" << endl;//It was already up
nfound = false;
}
else {//it wasn't
if (!EnumWindows(FindWindowBySubstr, (LPARAM)argv[1])) {//loop through every single window
nfound = false;
}
else {
Sleep(1000);
}
}
}
else {
cout << "found absolute result" << endl;
SwitchToThisWindow(windowHandle, true);//switch to the located window
nfound = false;
}
}
}
}
else if (argc == 1) {
cout << "This program takes one input, part of the window name, and waits for that window to load" << endl;
}
else {
cout << "How did you manage to pass a negative number of flags?" << endl;
}
return 0;
}
validateGoogleChrome.exe source (эта программа проверяет, был ли настроен Chrome. Предполагается, что имя пользователя компьютера совпадает с именем пользователя учетной записи Google Apps. Его также необходимо запустить в %LOCALAPPDATA%\Google\Chrome\User Data\Default\Preferences
):
// validateGoogleChrome.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <windows.h>
#include <lm.h>
using namespace std;
string gUname() {
char username[UNLEN + 1];
DWORD size = UNLEN + 1;
GetUserNameA(username, &size);
stringstream conv;
string uname = "";
conv << username;
conv >> uname;
cout << "username:" << uname << endl;
return uname;
}
int main()
{
string line;
string query = gUname();
ifstream file("Preferences");
if (file.is_open()) {
while (getline(file, line, '\n')) {
if (line.find(query) != string::npos) {
cout << "passed" << endl;
return 0;
}
else {
cout << "fail" << endl;
return 1;
}
}
}
else {
cout << "ERROR: Chrome preferences file not found" << endl;
return 2;
}
}
Надеюсь, этот код привел вас в ужас, когда вы нашли лучшее решение.