Enable extension programmatically in incognito mode on ubuntu - google-chrome

We are setting kiosk-type workstations with chromium browser running in incognito mode. There is a need to have redux-devtools extension for development purposes.
We managed in install it using scripts. Basically uploaded bundles and manifest.json to
/usr/share/chromium-browser/extensions
In non-incognito mode it works. And there is a way to enable it in incognito move using UI (settings for the extension).
But the thing is that we have no access for this interaction and we have to do it somehow programmatically. Looks like its not some browser setting but extension's one. Is there any way to do it using bash or smth. similar?

There is no direct way to do it. But I've manage to do this in no so obvious way. I made it work by directly modifying preferences file. To make it work all chrome instances should be closed. Also instead of installing extension just unpack it somewhere you know. So here is how to start chrome
`chrome --incognito --load-extension=<path/to/unpacked/extension>`
This will start chrome with extension installed meaning that some preference entries will be created. Now we need to modify value that responsible for allowing extension in incognito mode. For this I wrote a small python3 script:
extension_incognito_enabled.py
import json
import os
import sys
google_chrome_preferences ="/home/j2ko/.config/google-chrome/Default/Preferences"
incognito_value = (False, True)[sys.argv[1] == "true"]
print("Closing all chrome instances")
os.system('killall chrome')
#As we load extension using --load-extension flag we can use path to it
field_to_compare="path"
field_value_to_compare_with="/home/j2ko/Downloads/isAllowedAccess"
jsonPreferences =""
with open(google_chrome_preferences, "r+") as jsonFile:
jsonPreferences = json.load(jsonFile)
settings = jsonPreferences["extensions"]["settings"]
for extension_name in settings:
extension_setting = settings[extension_name]
if extension_setting[field_to_compare] == field_value_to_compare_with:
extension_setting["incognito"] = incognito_value
print("Successfully modified file. Now incognito mode value is ", incognito_value)
break
with open(google_chrome_preferences, "w+") as jsonFile:
json.dump(jsonPreferences, jsonFile)
I've tested it using isAllowedAccess. So to suit your needs you need to modify script and provide proper values for field_value_to_compare_with (which actually equals to --load-extension value) and provide correct google_chrome_preferences value.
You can use script as :
extension_incognito_enabled.py true # to enable
extension_incognito_enabled.py false # to disable
If you only have python2 simply remove print lines and it should work as well.

Related

Can you set the download path for the Apparition driver?

I'm dabbing into switching over our acceptance tests to the Capybara/Apparition driver. I want to add specific Chrome browser preferences for the download path.
I can't find any documentation on this, and by the look of things I can't use a Chrome options object like I would with Capybara, Selenium and chromedriver, such as:
#options = Selenium::WebDriver::Chrome::Options.new
def specific_chrome_options
preferences = {
prompt_for_download: false,
default_directory: FilesDownloadHelper::PATH # custom profile needed to test file downloads
}
#options.add_preference(:download, preferences)
I've tried to set this with a '--user-data-dir' args and preferences file created during run, but it doesn't seem like it is picking it up.
Perhaps the driver is still in a beta state for these kind of things?
With apparition downloads should go to whatever directory Capybara.save_path is set to.

How to fix this "your system administrator has configured chrome to open an alternate browser to access"

I'm trying open an application in google chrome, when I launch the website chrome it redirects to IE and showing message "your system administrator has configured chrome to open an alternate browser to access" in chrome. How to overcome this issue
Behavior
You open a corporate site. For example,
http://legacy_SharePoint_2010.com
You will see a message: "Your
system administrator has configured chrome to open an alternate
browser to access"
Your IE 11 will be opened and your chrome tab will be closed:
Why this is happening
The behavior is controlled by the Chrome Policies (chrome://policy/)
When Policy is setup, chrome://browser-switch protocol is used to redirect to IE
The list of sites that will be forced to use IE 11 is listed in the registry, under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\BrowserSwitcherUrlList
You might need local admin permissions to modify or remove these registry keys
:
When your company forces such policy by default than sooner or later you have to update the policy in regedit again. Quite elegant solution could be to switch off/on the policy when needed. I do so with Python and winreg module (but could be similar in other languages):
import winreg
from itertools import count
def switch_reg_browser_switcher():
reg_handler = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
with winreg.OpenKey(reg_handler, r"SOFTWARE\Policies\Google\Chrome", 0, winreg.KEY_ALL_ACCESS) as regkey:
for i in count():
try:
val_name, curr_value, _ = winreg.EnumValue(regkey,i)
if val_name == 'BrowserSwitcherEnabled':
print(val_name, curr_value)
winreg.SetValueEx(regkey, val_name, 0, winreg.REG_DWORD, curr_value^1)
break
except OSError:
print('All keys iterated but "BrowserSwitcherEnabled" not found')
break
print('Updating Windows registry to reset company policy...')
switch_reg_browser_switcher()
Or a simple solution in Batch file:
#echo off
set regkey="HKLM\SOFTWARE\Policies\Google\Chrome"
REG QUERY %regkey% /v BrowserSwitcherEnabled
if %errorlevel% equ 0 ( REG ADD %regkey% /v BrowserSwitcherEnabled /t REG_DWORD /d 0 /f
) else (echo no such value)
My motivation to do this was webscraping with Selenium (Chrome driver is much faster than IE) and no power to force my company to change policy.

Karma/Testacular opens browser without extensions

When I run Karma (formerly Testacular) with 'browsers' configured to 'Chrome' and 'Firefox', 2 browser instances indeed open, however the extensions/plugins appear to be missing while I want them running with my tests.
I've configured:
CHROME_BIN=C:\Program Files (x86)\Google\Chrome\Application\chrome.exe and FIREFOX_BIN=C:\Program Files (x86)\Mozilla Firefox\firefox.exe
It kinda looks like the launched Chrome instance is of a different installation or something, as it doesn't have all my Chrome bookmarks (neither the extensions, as written).
Any idea?
If you change the index.js like this:
this._getOptions = function(url) {
// Chrome CLI options
// http://peter.sh/experiments/chromium-command-line-switches/
return [
'--user-data-dir=' + this._tempDir,
'--no-default-browser-check',
'--no-first-run',
'--disable-default-apps',
'--disable-popup-blocking',
'--start-maximized',
'--load-extension=' + '<your path to the extension>/2.0_0'
].concat(flags, [url]);
where
<your path to the extionsion>
is something like this:
/Users/dannyb/Library/Application Support/Google/Chrome/Default/Extensions/hmhgeddbohgjknpmjagkdomcpobmllji
That weird number is the extionsion ID that you can find in your extensions page in chrome.
If you look at how chrome is run on karma, along with some other command line flags, it disables default apps
on start up. I myself am looking for how to turn these features off, but no luck yet.
https://github.com/karma-runner/karma-chrome-launcher/blob/master/index.js

Using --js-flags in Google Chrome to get --trace output

I've looked through various sources online and done a number of Google searches, but I can't seem to find any specific instructions as to how to work with the V8 --trace-* flags in Google Chrome. I've seen a few "You can do this as well in Chrome", but I haven't been able to find what I'm looking for, which is output like this: (snippets are near the near bottom of the post) Optomizing for V8.
I found reference that the data is logged to a file: Profiling Chromium with V8 and I've found that the file is likely named v8.log: (Lost that link) but I haven't found any clues as to how to generate that file, or where it is located. It didn't appear to be in the chrome directory or the user directory.
Apparently I need to enable .map files for chrome.dll as well, but I wasn't able to find anything to help me with that.
The reason I would prefer to use Chrome's V8 for this as opposed to building V8 and using a shell is because the JavaScript I would like to test makes use of DOM, which I do not believe would be included in the V8 shell. However if it is, that would be great to know, then I can rewrite the code to work sans-html file and test. But my guess is that V8 by itself is sans-DOM access, like node.js
So to sum things up;
Running Google Chrome Canary on Windows 7 ultimate x64
Shortcut target is "C:\Users\ArkahnX\AppData\Local\Google\Chrome SxS\Application\chrome.exe" --no-sandbox --js-flags="--trace-opt --trace-bailout --trace-deop" --user-data-dir=C:\chromeDebugProfile
Looking for whether this type of output can be logged from chrome
If so, where would the log be?
If not, what sort of output should I expect, and again, where could I find it?
Thank you for any assistance!
Amending with how I got the answer to work for me
Using the below answer, I installed python to it's default directory, and modified the script so it had the full path to chrome. From there I set file type associations to .py files to python and executed the script. Now every time I open Chrome Canary it will run that python script (at least until I restart my pc, then I'll have to run that script again)
The result is exactly what I was looking for!
On Windows stdout output is suppressed by the fact that chrome.exe is a GUI application. You need to flip Subsystem field in the PE header from IMAGE_SUBSYSTEM_WINDOWS_GUI to WINDOWS_SUBSYSTEM_WINDOWS_CUI to see what V8 outputs to stdout.
You can do it with the following (somewhat hackish) Python script:
import mmap
import ctypes
GUI = 2
CUI = 3
with open("chrome.exe", "r+b") as f:
map = mmap.mmap(f.fileno(), 1024, None, mmap.ACCESS_WRITE)
e_lfanew = (ctypes.c_uint.from_buffer(map, 30 * 2).value)
subsystem = ctypes.c_ushort.from_buffer(map, e_lfanew + 4 + 20 + (17 * 4))
if subsystem.value == GUI:
subsystem.value = CUI
print "patched: gui -> cui"
elif subsystem.value == CUI:
subsystem.value = GUI
print "patched: cui -> gui"
else:
print "unknown subsystem: %x" % (subsystem.value)
Close all Chrome instances and execute this script. When you restart chrome.exe you should see console window appear and you should be able to redirect stdout via >.
If your not keen on hacking the PE entry of chrome then there is alternative for windows.
Because the chrome app doesn't create a console stdout on windows all tracing in v8 (also d8 compiler) is sent to the OutputDebugString instead.
The OutputDebugString writes to a shared memory object that can be read by any other application.
Microsoft has a tool called DebugView which monitors and if required also stream to a log file.
DebugView is free and downloadable from microsoft: http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx

Save the console.log in Chrome to a file

Does anyone know of a way to save the console.log output in Chrome to a file? Or how to copy the text out of the console?
Say you are running a few hours of functional tests and you've got thousands of lines of console.log output in Chrome. How do you save it or export it?
Good news
Chrome dev tools now allows you to save the console output to a file natively
Open the console
Right-click
Select "save as.."
Chrome Developer instructions here.
I needed to do the same thing and this is the solution I found:
Enable logging from the command line using the flags:
--enable-logging --v=1
This logs everything Chrome does internally, but it also logs all the console.log() messages as well. The log file is called chrome_debug.log and is located in the User Data Directory which can be overridden by supplying --user-data-dir=PATH (more info here).
Filter the log file you get for lines with CONSOLE(\d+).
Note that console logs do not appear with --incognito.
I have found a great and easy way for this.
In the console - right click on the console logged object
Click on 'Store as global variable'
See the name of the new variable - e.g. it is variableName1
Type in the console: JSON.stringify(variableName1)
Copy the variable string content: e.g. {"a":1,"b":2,"c":3}
Go to some JSON online editor:
e.g. https://jsoneditoronline.org/
There is an open-source javascript plugin that does just that, but for any browser - debugout.js
Debugout.js records and save console.logs so your application can access them. Full disclosure, I wrote it. It formats different types appropriately, can handle nested objects and arrays, and can optionally put a timestamp next to each log. You can also toggle live-logging in one place, and without having to remove all your logging statements.
For better log file (without the Chrome-debug nonsense) use:
--enable-logging --log-level=0
instead of
--v=1 which is just too much info.
It will still provide the errors and warnings like you would typically see in the Chrome console.
update May 18, 2020: Actually, I think this is no longer true. I couldn't find the console messages within whatever this logging level is.
This may or may not be helpful but on Windows you can read the console log using Event Tracing for Windows
http://msdn.microsoft.com/en-us/library/ms751538.aspx
Our integration tests are run in .NET so I use this method to add the console log to our test output. I've made a sample console project to demonstrate here: https://github.com/jkells/chrome-trace
--enable-logging --v=1 doesn't seem to work on the latest version of Chrome.
For Google Chrome Version 84.0.4147.105 and higher,
just right click and click 'Save as' and 'Save'
then, txt file will be saved
A lot of good answers but why not just use JSON.stringify(your_variable) ? Then take the contents via copy and paste (remove outer quotes). I posted this same answer also at: How to save the output of a console.log(object) to a file?
There is another open-source tool which allows you to save all console.log output in a file on your server - JS LogFlush (plug!).
JS LogFlush is an integrated JavaScript logging solution which include:
cross-browser UI-less replacement of console.log - on client side.
log storage system - on server side.
Demo
If you're running an Apache server on your localhost (don't do this on a production server), you can also post the results to a script instead of writing it to console.
So instead of console.log, you can write:
JSONP('http://localhost/save.php', {fn: 'filename.txt', data: json});
Then save.php can do this
<?php
$fn = $_REQUEST['fn'];
$data = $_REQUEST['data'];
file_put_contents("path/$fn", $data);
Right-click directly on the logged value you want to copy
In the right-click menu, select "Store as global variable"
You'll see the value saved as something like "temp1" on the next line in the console
In the console, type copy(temp1) and hit return (replace temp1 with the variable name from the previous step). Now the logged value is copied to your clipboard.
Paste the values to wherever you want
This is especially good as an approach if you don't want to mess with changing flags/settings in Chrome and don't want to deal with JSON stringifying and parsing etc.
Update: I just found this explanation of what I suggested with images that's easier to follow https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html
These days it's very easy - right click any item displayed in the console log and select save as and save the whole log output to a file on your computer.
On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.
export CHROME_LOG_FILE=chrome.log
the other solutions in this thread weren't working on my mac. Here's a logger that saves a string representation intermittently using ajax. use it with console.save instead of console.log
var logFileString="";
var maxLogLength=1024*128;
console.save=function(){
var logArgs={};
for(var i=0; i<arguments.length; i++) logArgs['arg'+i]=arguments[i];
console.log(logArgs);
// keep a string representation of every log
logFileString+=JSON.stringify(logArgs,null,2)+'\n';
// save the string representation when it gets big
if(logFileString.length>maxLogLength){
// send a copy in case race conditions change it mid-save
saveLog(logFileString);
logFileString="";
}
};
depending on what you need, you can save that string or just console.log it and copy and paste. here's an ajax for you in case you want to save it:
function saveLog(data){
// do some ajax stuff with data.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {}
}
xhttp.open("POST", 'saveLog.php', true);
xhttp.send(data);
}
the saveLog.php should append the data to a log file somewhere. I didn't need that part so I'm not including it here. :)
https://www.google.com/search?q=php+append+to+log
This answer might seem specifically related, but specifically for Network Log, you can visit the following link.
The reason I've post this answer is because in my case, the console.log printed a long truncated text so I couldn't get the value from the console. I solved by getting the api response I was printing directly from the network log.
chrome://net-export/
There you may see a similar windows to this, just press the Start Logging to Disk button and that's it:
Create a batch file using below command and save it as ChromeDebug.bat in your desktop.
start chrome --enable-logging --v=1
Close all other Chrome tabs and windows.
Double click ChromeDebug.bat file which will open Chrome and a command prompt with Chrome icon in taskbar.
All the web application logs will be stored in below path.
Run the below path in Run command to open chrome log file
%LocalAppData%\Google\Chrome\User Data\chrome_debug.log