Download the PHP package gsouf/chromium without Composer
On this page you can find all versions of the php package gsouf/chromium. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package chromium
Chrome PHP
This library lets you start playing with chrome/chromium in headless mode from PHP.
Can be used synchronously and asynchronously!
Features
- Open Chrome or Chromium browser from php
- Create pages and navigate to pages
- Take screenshots
- Evaluate javascript on the page
- Make PDF
- Emulate mouse
- Emulate keyboard
- Always IDE friendly
Happy browsing!
Requirements
Requires PHP 7.4-8.3 and a Chrome/Chromium 65+ executable.
Note that the library is only tested on Linux but is compatible with macOS and Windows.
Installation
The library can be installed with Composer and is available on packagist under chrome-php/chrome:
Usage
It uses a simple and understandable API to start Chrome, to open pages, take screenshots, crawl websites... and almost everything that you can do with Chrome as a human.
Using different Chrome executable
When starting, the factory will look for the environment variable "CHROME_PATH"
to use as the Chrome executable.
If the variable is not found, it will try to guess the correct executable path according to your OS or use "chrome"
as the default.
You are also able to explicitly set up any executable of your choice when creating a new object. For instance "chromium-browser"
:
Debugging
The following example disables headless mode to ease debugging
Other debug options:
About debugLogger
: this can be any of a resource string, a resource, or an object implementing
LoggerInterface
from Psr\Log (such as monolog
or apix/log).
API
Browser Factory
Options set directly in the createBrowser
method will be used only for a single browser creation. The default options will be ignored.
Options set using the setOptions
and addOptions
methods will persist.
Available options
Here are the options available for the browser factory:
Option name | Default | Description |
---|---|---|
connectionDelay |
0 |
Delay to apply between each operation for debugging purposes |
customFlags |
none | An array of flags to pass to the command line. Eg: ['--option1', '--option2=someValue'] |
debugLogger |
null |
A string (e.g "php://stdout"), or resource, or PSR-3 logger instance to print debug messages |
disableNotifications |
false |
Disable browser notifications |
enableImages |
true |
Toggles loading of images |
envVariables |
none | An array of environment variables to pass to the process (example DISPLAY variable) |
headers |
none | An array of custom HTTP headers |
headless |
true |
Enable or disable headless mode |
ignoreCertificateErrors |
false |
Set Chrome to ignore SSL errors |
keepAlive |
false |
Set to true to keep alive the Chrome instance when the script terminates |
noSandbox |
false |
Enable no sandbox mode, useful to run in a docker container |
noProxyServer |
false |
Don't use a proxy server, always make direct connections. Overrides other proxy settings. |
proxyBypassList |
none | Specifies a list of hosts for whom we bypass proxy settings and use direct connections |
proxyServer |
none | Proxy server to use. usage: 127.0.0.1:8080 (authorisation with credentials does not work) |
sendSyncDefaultTimeout |
5000 |
Default timeout (ms) for sending sync messages |
startupTimeout |
30 |
Maximum time in seconds to wait for Chrome to start |
userAgent |
none | User agent to use for the whole browser (see page API for alternative) |
userDataDir |
none | Chrome user data dir (default: a new empty dir is generated temporarily) |
userCrashDumpsDir |
none | The directory crashpad should store dumps in (crash reporter will be enabled automatically) |
windowSize |
none | Size of the window. usage: $width, $height - see also Page::setViewport |
excludedSwitches |
none | An array of Chrome flags that should be removed from the default set (example --enable-automation) |
Persistent Browser
This example shows how to share a single instance of Chrome for multiple scripts.
The first time the script is started we use the browser factory in order to start Chrome, afterwards we save the uri to connect to this browser in the file system.
The next calls to the script will read the uri from that file in order to connect to the Chrome instance instead of creating a new one. If Chrome was closed or crashed, a new instance is started again.
Browser API
Create a new page (tab)
Get opened pages (tabs)
Close the browser
Set a script to evaluate before every page created by this browser will navigate
Page API
Navigate to an URL
When using $navigation->waitForNavigation()
you will wait for 30sec until the page event "loaded" is triggered.
You can change the timeout or the event to listen for:
Available events (in the order they trigger):
Page::DOM_CONTENT_LOADED
: dom has completely loadedPage::FIRST_CONTENTFUL_PAINT
: triggered when the first non-white content element is painted on the screenPage::FIRST_IMAGE_PAINT
: triggered when the first image is painted on the screenPage::FIRST_MEANINGFUL_PAINT
: triggered when the primary content of a page is visible to the userPage::FIRST_PAINT
: triggered when any pixel on the screen is painted, including the browser's default background colorPage::INIT
: connection to DevTools protocol is initializedPage::INTERACTIVE_TIME
: scripts have finished loading and the main thread is no longer blocked by rendering or other tasksPage::LOAD
: (default) page and all resources are loadedPage::NETWORK_IDLE
: page has loaded, and no network activity has occurred for at least 500ms
When you want to wait for the page to navigate 2 main issues may occur. First, the page is too long to load and second, the page you were waiting to be loaded has been replaced. The good news is that you can handle those issues using a good old try-catch:
Evaluate script on the page
Once the page has completed the navigation you can evaluate arbitrary script on this page:
Sometimes the script you evaluate will click a link or submit a form, in this case, the page will reload and you will want to wait for the new page to reload.
You can achieve this by using $page->evaluate('some js that will reload the page')->waitForPageReload()
.
An example is available in form-submit.php
Call a function
This is an alternative to evaluate
that allows calling a given function with the given arguments in the page context:
Add a script tag
That's useful if you want to add jQuery (or anything else) to the page:
You can also use an URL to feed the src attribute:
Set the page HTML
You can manually inject html to a page using the method.
When a page's HTML is updated, we'll wait for the page to unload. You can specify how long to wait and which event to wait for through two optional parameters. This defaults to 3000ms and the "load" event.
Note that this method will not append to the current page HTML, it will completely replace it.
Get the page HTML
You can get the page HTML as a string using the method.
Add a script to evaluate upon page navigation
If your script needs the dom to be fully populated before it runs then you can use the option "onLoad":
Set viewport size
This feature allows changing the size of the viewport (emulation) for the current page without affecting the size of
all the browser's pages (see also option "windowSize"
of BrowserFactory::createBrowser).
Make a screenshot
Screenshot an area on a page
You can use the option "clip" to choose an area on a page for the screenshot
Full-page screenshot
You can also take a screenshot for the full-page layout (not only the viewport) using $page->getFullPageClip
with attribute captureBeyondViewport = true
Print as PDF
Options headerTemplate
and footerTemplate
:
Should be valid HTML markup with the following classes used to inject printing values into them:
- date: formatted print date
- title: document title
- url: document location
- pageNumber: current page number
- totalPages: total pages in the document
Save downloads
You can set the path to save downloaded files.
Mouse API
The mouse API is dependent on the page instance and allows you to control the mouse's moves, clicks and scroll.
You can emulate the mouse wheel to scroll up and down in a page, frame, or element.
Finding elements
The find
method will search for elements using querySelector and move the cursor to a random position over it.
This method will attempt to scroll right and down to bring the element to the visible screen. If the element is inside an internal scrollable section, try moving the mouse to inside that section first.
Keyboard API
The keyboard API is dependent on the page instance and allows you to type like a real user.
To impersonate a real user you may want to add a delay between each keystroke using the method:
Key combinations
The methods press
, type
, and release
can be used to send key combinations such as ctrl + v
.
You can press the same key several times in sequence, this is the equivalent to a user pressing and holding the key. The release event, however, will be sent only once per key.
Key aliases
Key | Aliases |
---|---|
Control | Control , Ctrl , Ctr |
Alt | Alt , AltGr , Alt Gr |
Meta | Meta , Command , Cmd |
Shift | Shift |
Cookie API
You can set and get cookies for a page:
Set Cookie
Get Cookies
Set user agent
You can set up a user-agent per page:
See also BrowserFactory option userAgent
to set up it for the whole browser.
Advanced usage
The library ships with tools that hide all the communication logic but you can use the tools used internally to communicate directly with Chrome debug protocol.
Example:
Create a session and send a message to the target
Debugging
You can ease the debugging by setting a delay before each operation is made:
Browser (standalone)
Interacting with DOM
Find one element on a page by CSS selector:
Find all elements inside another element by CSS selector:
Find all elements on a page by XPath selector:
Wait for an element by CSS selector:
If a string is passed to Page::waitUntilContainsElement
, an instance of
CSSSelector
is created for you by Page::waitForElement
. To use other
selectors, you can pass an instance of the required Selector
.
Wait for element by XPath selector:
You can send out a text to an element or click on it:
You can upload file to file from the input:
You can get element text or attribute:
Contributing
See CONTRIBUTING.md for contribution details.
License
This project is licensed under the The MIT License (MIT).
All versions of chromium with dependencies
chrome-php/wrench Version ^1.7
evenement/evenement Version ^3.0.1
monolog/monolog Version ^1.27.1 || ^2.8 || ^3.2
psr/log Version ^1.1 || ^2.0 || ^3.0
symfony/filesystem Version ^4.4 || ^5.0 || ^6.0 || ^7.0
symfony/polyfill-mbstring Version ^1.26
symfony/process Version ^4.4 || ^5.0 || ^6.0 || ^7.0