0

I have a chrome extension which when activated (clicked or keyboard-shortcut ) parses some data from the given site and sends it to my server. I need to automate this task to run daily at a specific time most preferably in headless mode.

The extension was loaded using a .crx file. The extension can be activated by clicking the extension icon or by pressing the alt+p keyboard shortcut.alt+p. Trying to simulate the keypress using Selenium doesn't seem to work, but other keyboard shortcuts, like ctrl+A, do.

from selenium.webdriver.common.action_chains import ActionChains
keyAction = ActionChains(driver)
keyAction.key_down(Keys.ALT).send_keys("p").key_up(Keys.ALT)

How to effectively simulate this shortcut? Is there any other way I can activate this extension?

Mohamed Irfan
  • 125
  • 1
  • 7
  • Don't send via webdriver because this hotkey is not a part of the web layer. Send it using a [standard module](https://stackoverflow.com/questions/13564851/how-to-generate-keyboard-events). – wOxxOm May 21 '23 at 15:45

1 Answers1

1

You can utilize the Chrome DevTools Protocol (CDP) in Selenium to activate a Chrome extension after launching the Chrome browser.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# Path to your Chrome WebDriver executable
webdriver_path = '/path/to/chromedriver'

# Path to the extension CRX file
extension_path = '/path/to/extension.crx'

# Create a ChromeOptions object
options = Options()

# Add the extension path to the ChromeOptions
options.add_argument(f'--load-extension={extension_path}')

# Create a ChromeDriverService instance
service = Service(webdriver_path)

# Create a WebDriver with the ChromeDriverService and ChromeOptions
driver = webdriver.Chrome(service=service, options=options)

# Activate the extension using the Chrome DevTools Protocol
dev_tools = driver.execute_cdp_cmd('Browser.enable', {})
driver.execute_cdp_cmd('Browser.activateTarget', {'targetId': driver.current_url})

# Now you can use the driver to interact with the activated extension
# For example, you can open a URL and interact with the extension on that page
driver.get('https://example.com')

By adding the --load-extension argument to the ChromeOptions, the WebDriver will launch Chrome with the specified extension loaded. Then, using the Chrome DevTools Protocol, you can activate the extension by executing the Browser.activateTarget command.