Skip to content

Commit

Permalink
chore: implement context.backgroundPages (#1532)
Browse files Browse the repository at this point in the history
Reference #1530
  • Loading branch information
yury-s authored Apr 2, 2024
1 parent f497bcc commit 452effb
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom

| | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: |
| Chromium <!-- GEN:chromium-version -->124.0.6367.8<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Chromium <!-- GEN:chromium-version -->124.0.6367.18<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| WebKit <!-- GEN:webkit-version -->17.4<!-- GEN:stop --> ||||
| Firefox <!-- GEN:firefox-version -->124.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,23 @@
*/
public interface BrowserContext extends AutoCloseable {

/**
* <strong>NOTE:</strong> Only works with Chromium browser's persistent context.
*
* <p> Emitted when new background page is created in the context.
* <pre>{@code
* Page backgroundPage = context.waitForBackgroundPage(() -> {
* page.getByText("activate extension").click();
* });
* System.out.println(backgroundPage.evaluate("location.href"));
* }</pre>
*/
void onBackgroundPage(Consumer<Page> handler);
/**
* Removes handler that was previously added with {@link #onBackgroundPage onBackgroundPage(handler)}.
*/
void offBackgroundPage(Consumer<Page> handler);

/**
* Emitted when Browser context gets closed. This might happen because of one of the following:
* <ul>
Expand Down Expand Up @@ -542,6 +559,14 @@ public WaitForPageOptions setTimeout(double timeout) {
* @since v1.8
*/
void addInitScript(Path script);
/**
* <strong>NOTE:</strong> Background pages are only supported on Chromium-based browsers.
*
* <p> All existing background pages in the context.
*
* @since v1.11
*/
List<Page> backgroundPages();
/**
* Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
private final TracingImpl tracing;
private final APIRequestContextImpl request;
final List<PageImpl> pages = new ArrayList<>();
final List<PageImpl> backgroundPages = new ArrayList<>();

final Router routes = new Router();
private boolean closeWasCalled;
private final WaitableEvent<EventType, ?> closePromise;
Expand Down Expand Up @@ -81,6 +83,7 @@ static class HarRecorder {
}

enum EventType {
BACKGROUNDPAGE,
CLOSE,
CONSOLE,
DIALOG,
Expand Down Expand Up @@ -128,6 +131,16 @@ String effectiveCloseReason() {
return null;
}

@Override
public void onBackgroundPage(Consumer<Page> handler) {
listeners.add(EventType.BACKGROUNDPAGE, handler);
}

@Override
public void offBackgroundPage(Consumer<Page> handler) {
listeners.remove(EventType.BACKGROUNDPAGE, handler);
}

@Override
public void onClose(Consumer<BrowserContext> handler) {
listeners.add(EventType.CLOSE, handler);
Expand Down Expand Up @@ -324,6 +337,11 @@ public void addInitScript(Path path) {
});
}

@Override
public List<Page> backgroundPages() {
return new ArrayList<>(backgroundPages);
}

private void addInitScriptImpl(String script) {
JsonObject params = new JsonObject();
params.addProperty("source", script);
Expand Down Expand Up @@ -712,6 +730,10 @@ protected void handleEvent(String event, JsonObject params) {
if (page.opener() != null && !page.opener().isClosed()) {
page.opener().notifyPopup(page);
}
} else if ("backgroundPage".equals(event)) {
PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString());
backgroundPages.add(page);
listeners.notify(EventType.BACKGROUNDPAGE, page);
} else if ("bindingCall".equals(event)) {
BindingCall bindingCall = connection.getExistingObject(params.getAsJsonObject("binding").get("guid").getAsString());
BindingCallback binding = bindings.get(bindingCall.name());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ void notifyPopup(PageImpl popup) {
void didClose() {
isClosed = true;
browserContext.pages.remove(this);
browserContext.backgroundPages.remove(this);
listeners.notify(EventType.CLOSE, this);
}

Expand Down
45 changes: 45 additions & 0 deletions playwright/src/test/java/com/microsoft/playwright/TestLaunch.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,18 @@

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.junit.jupiter.api.io.TempDir;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static com.microsoft.playwright.Utils.mapOf;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.*;

public class TestLaunch extends TestBase {

Expand All @@ -40,4 +50,39 @@ void passEnvVar() {
options.setEnv(mapOf("DEBUG", "pw:protocol"));
launchBrowser(options);
}

public static boolean canRunHeaded() {
// On linux headed browser requires xvfb.
return isHeadful() || isMac || isWindows;
}

public static boolean canRunExtensionTest() {
return canRunHeaded() && isChromium();
}

@Test
@EnabledIf(value="com.microsoft.playwright.TestLaunch#canRunExtensionTest", disabledReason="Only Chromium Headed")
void shouldReturnBackgroundPages(@TempDir Path tmpDir) throws IOException {
Path profileDir = tmpDir.resolve("profile");
Files.createDirectories(profileDir);
String extensionPath = Paths.get("src/test/resources/simple-extension").toAbsolutePath().toString();
initBrowserType();
BrowserContext context = browserType.launchPersistentContext(profileDir, new BrowserType.LaunchPersistentContextOptions()
.setHeadless(false)
.setArgs(asList(
"--disable-extensions-except=" + extensionPath,
"--load-extension=" + extensionPath
)));
List<Page> backgroundPages = context.backgroundPages();
context.onBackgroundPage(page1 -> backgroundPages.add(page1));
context.waitForCondition(() -> !backgroundPages.isEmpty(),
new BrowserContext.WaitForConditionOptions().setTimeout(10_000));
Page backgroundPage = backgroundPages.get(0);
assertNotNull(backgroundPage);
assertTrue(context.backgroundPages().contains(backgroundPage));
assertFalse(context.pages().contains(backgroundPage));
context.close();
assertEquals(0, context.pages().size());
assertEquals(0, context.backgroundPages().size());
}
}
2 changes: 1 addition & 1 deletion scripts/CLI_VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.43.0-beta-1711493485000
1.44.0-alpha-2024-04-02

0 comments on commit 452effb

Please sign in to comment.