Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] browser.newContext: Unknown permission: clipboard-read for webkit #13037

Open
amrsa1 opened this issue Mar 24, 2022 · 28 comments
Open

[BUG] browser.newContext: Unknown permission: clipboard-read for webkit #13037

amrsa1 opened this issue Mar 24, 2022 · 28 comments

Comments

@amrsa1
Copy link

amrsa1 commented Mar 24, 2022

Context:

  • Playwright Version: 1.20.1
  • Operating System: Mac
  • Node.js version: 14.6
  • Browser: webkit

Code Snippet

const config: PlaywrightTestConfig = {
    globalTeardown: require.resolve('../src/utils/teardown'),
    workers: configList.workers,
    use: {
        contextOptions: {
            userAgent: configList.userAgent,
            permissions: ['clipboard-read', 'clipboard-write']
        },
    test('test', async ({ browserName, page }) => {
        expect(await page.screenshot({ fullPage: true, timeout: 4000 })).toMatchSnapshot(`${browserName}-EN.png`);
    });

Describe the bug

Test is failing for webkit browser, if config file contains permissions: ['clipboard-read', 'clipboard-write'] however there is not any clipboard event is being used in this test

error :

  3) [Desktop Firefox] › search/.test.ts:38:5 › Landing page Test Suite › test

    browser.newContext: Unknown permission: clipboard-read
@dgozman
Copy link
Contributor

dgozman commented Mar 24, 2022

Indeed, clipboard-read and clipboard-write are only supported in Chromium.

@amrsa1
Copy link
Author

amrsa1 commented Mar 24, 2022

@dgozman Could it be enhanced, so that if its included in the config file it will has no effect on webkit rather than make it fail, as the same config ia running agaisnt chrome and firefox in the same instance as well

@mirao
Copy link

mirao commented Apr 15, 2022

I had the same issue in Firefox, CodeceptJS + Playwright.
In Firefox no permission is needed to have working "copy of text to clipboard" (note it works in secure sites only).

It would be great if Playwright was able to suppress the error browser.newContext: Unknown permission: clipboard-write if given browser doesn't provide that feature.
Currently I must allow such setting in test for Chromium and not for Firefox which makes tests more complex.

@amrsa1
Copy link
Author

amrsa1 commented May 22, 2022

Any update regarding this topic

@rahulvramesh
Copy link

any update ?

@dgozman
Copy link
Contributor

dgozman commented Jul 14, 2022

We suggest to set permission per browser. Most likely, you already have test projects with different browsers configured, so just move permission to the respective project.

// playwright.config.ts

export default {
  projects: [
    {
      name: 'chromium',
      browserName: 'chromium',
      use: {
        contextOptions: {
          // chromium-specific permissions
          permissions: ['clipboard-read', 'clipboard-write'],
        },
      },
    },
    {
      name: 'firefox',
      browserName: 'firefox',
      use: {
        contextOptions: {
          // firefox-specific permissions
          permissions: ['geolocation'],
        },
      },
    },
  ],
};

@rahulvramesh
Copy link

rahulvramesh commented Jul 15, 2022

thanks, @dgozman , will try it out though somehow, the below code worked for me, which is similar to something I tried first.

const browser = await chromium.launch({headless: false});
  const context = await browser.newContext({
    permissions: ['geolocation', 'microphone', 'camera'],
    colorScheme: 'dark',
    recordVideo: {
      dir: 'videos/',
      size: { width: 1920, height: 1080 },
    }
  });

@dimitur2204
Copy link

How can I even test copying and pasting from Firefox or Webkit then? Is it impossible currently?

@IgorKoryapin
Copy link

faced the same problem, did not find a solution

@gselsidi
Copy link

@dgozman does safari support read write permissions? how do we set them? as it fails with the above chromium settings

@aalayoubi
Copy link

@dimitur2204 I'm having the same issue, did you figure it out?

@dimitur2204
Copy link

@dimitur2204 I'm having the same issue, did you figure it out?

No I did not

@aalayoubi
Copy link

@dimitur2204 I had to skip the test being run on firefox because I couldn't find a way around it

@Palak-Jethwani
Copy link

This is indeed an issue which must be fixed in Playwright. I am using Cucumber as my test runner so I can't use projects as well in config. And my tests fail in firefox and webkit because of unknown permission error. Please fix asap or provide at least a workaround.

@moshikd
Copy link

moshikd commented Jul 9, 2023

any update on this issue?? i'm facing it on webkit and firefox ? @dgozman @mxschmitt

@erickbelfy
Copy link

im also facing the same issue.

@yakovkurochkin
Copy link

yakovkurochkin commented Aug 7, 2023

Workaround for Firefox:

test('Firefox clipboard', async ({}) => {
  const browser = await firefox.launch({
    firefoxUserPrefs: {
      'dom.events.asyncClipboard.readText': true,
      'dom.events.testing.asyncClipboard': true,
    },
  });

  const page = await browser.newPage();

  await page.goto('https://copy-current-url-button.webflow.io/');
  await page.locator('#copy-status').click();

  const clipboardContents = await page.evaluate('navigator.clipboard.readText()');

  console.log(clipboardContents);
});

@porleaaron
Copy link

This approach should work

projects: [{
  name: "chromium",
  use: {
    ...devices["Desktop Chrome"],
    contextOptions: {
      // chromium-specific permissions
      permissions: ['clipboard-read', 'clipboard-write'],
    },
  },
},


{
  name: "firefox",
  use: {
    ...devices["Desktop Firefox"],
    launchOptions: {
      firefoxUserPrefs: {
        'dom.events.asyncClipboard.readText': true,
        'dom.events.testing.asyncClipboard': true,
      },
    }
  },
},

{
  name: "webkit",
  use: { ...devices["Desktop Safari"] },
}]

@krachtstefan
Copy link

krachtstefan commented Sep 29, 2023

This worked for me, except in Safari. If anyone can give me a hint on how to setup the proper permissions for safari, I would be very happy.

In the meantime I solved it by mocking the clipborad API and find it might be worth sharing:

e2e/utils/index.ts

import { Page } from "@playwright/test";

/**
 * this will mock the browsers clipboard API, since it might not be available in the test environment
 * due to invalid permissions. It's recommended to use this function in the beforeAll or beforeEach hook
 * of the test to inject the mock into the page very early. It will e.g. not work if it's called after
 * page.goto() has been called.
 */
export const mockClipboardAPI = async (page: Page) =>
  await page.addInitScript(() => {
    // create a mock of the clipboard API
    const mockClipboard = {
      clipboardData: "",
      writeText: async (text: string) => {
        mockClipboard.clipboardData = text;
      },
      readText: async () => mockClipboard.clipboardData,
    };

    // override the native clipboard API
    Object.defineProperty(navigator, "clipboard", {
      value: mockClipboard,
      writable: false,
      enumerable: true,
      configurable: true,
    });
  });

e2e/mytest.ts

import { mockClipboardAPI } from "e2e/utils/testutils";

test.beforeEach(async ({ page }) => {
  await mockClipboardAPI(page);
});

test("I am a test that needs to validate that some text was copied into the clipboard", async ({
  page,
}) => {
  /**
   * this might be replaces by an interaction with the UI,
   * in which the user copies something into the clipboard
   */
  await page.evaluate(() =>
    navigator.clipboard.writeText("I was copied into the clipboard")
  );

  const clipboardText = await page.evaluate(() =>
    /**
     * this will call the mock instead of the real clipboard API. To make
     * sure the mock was actually used, go to the mockClipboardAPI function
     * and change the return value of the readText function to some test
     * data and see if will end up here.
     */
    navigator.clipboard.readText()
  );

  expect(clipboardText).toBe("I was copied into the clipboard");
});

@agusmakmun
Copy link

agusmakmun commented Nov 15, 2023

I have the same issue, and using selector for safari:

try {
  email = await page.evaluate("navigator.clipboard.readText()");
} catch (e) {
  // this case is to handle the safari browser where having the clipboard permission
  // https://github.com/microsoft/playwright/issues/13037
  let emailLocator = await page.locator('//div[contains(@class, "cursor-pointer")]/p');
  email = await emailLocator.innerText();
}

Above case will need to wait until few times, to make it fast we can use the browserName fixture as a conditional:

test("something", async ({ page, browserName }) => {
  ...

  if (['webkit', 'Desktop Safari', 'Mobile Safari'].includes(browserName)) {
    let emailLocator = await page.locator('//div[contains(@class, "cursor-pointer")]/p');
    email = await emailLocator.innerText();
  } else {
    email = await page.evaluate("navigator.clipboard.readText()");
  }
})

dblanken-yale added a commit to yalesites-org/yalesites-automated-tests that referenced this issue Feb 20, 2024
Use a mock clipboard in order to determine if the copy button actually
copies text into the clipboard.  Thank you to krachtstefan for their
mockClipboardAPI implementation:
microsoft/playwright#13037 (comment)
@marcin-bojar
Copy link

same issue here, Safari does not allow to test copy-to-clipboard functionality, any timelines for the fix?

codemonkey800 added a commit to chanzuckerberg/cryoet-data-portal that referenced this issue Mar 8, 2024
Fixes the download E2E tests by making the following changes:

- Fix typos in workflow file that allows us to shard by browser
- Add clipboard permissions in playwright config for chromium and
firefox
- Replace `page.goto()` with `goTo()` util to reduce flakiness due to
JavaScript hydration
- Skip clipboard tests for webkit until support is added
-
microsoft/playwright#13037 (comment)

## Demo

Successful run:
https://github.com/chanzuckerberg/cryoet-data-portal/actions/runs/8207084715
dblanken-yale added a commit to yalesites-org/yalesites-automated-tests that referenced this issue Mar 14, 2024
* feat(playwright): specify YALESITES_URL override

* fix(search): search acknowledges there are breads

The original test that tested against no mention of the word "bread" or
"crumb" yielded no results.  However, we now talk about them in our
pages, so they have results.  Right now we ensure that they do exist
there.  Another test might be to visit those that are returned and
verify that the text actually exists, but that could be cumbersome, so
for now we just know that there should be 2 returned and test against
that.

* fix(search): search test uses unused search

It turns out we like to use "blah", so changed this to be something
rediculous that would never be on one of our pages.

* feat(accordion): add accordion tests

* feat(accordion): test accordion functionality

* feat(accordion): works for more browsers

Found out that our menu animation is causing tab issues in testing.  At
times it is tabbing into the menu before it animates away, causing false
positives.  Waiting the short bit seems to fix the issue, but it is
still a race condition.

* feat(snapshots): change snapshot folder

Change the snapshot folder from inside the tests folder to a snapshots folder for better separation.

* feat(action_banner): add action banner tests

* feat(button-link): add button link tests

* feat(calendar-list): add calendar list tests

* feat(callout): add callout tests

* feat(visreg): all visreg tests

This was an existing script we used to test between multiple sites.
We're including it here for now as to be able to use it and integrate it
into our overall testing here.

* feat(script): Script to compare two sites

* feat(custom-cards): tests for custom card

* feat(directory): add directory tests

* feat(divider): add divider tests

* feat(images): add base images

* feat(embed): add embed tests

* feat(event): add event tests

* feat(gallery): add gallery tests

* feat(grand-hero): add grand-hero tests

* feat(image): add image tests

* feat(media-grid): add media-grid tests

* feat(post-feed): add post-feed tests

* feat(pre-built-form): add pre-built-form tests

* feat(profile): add profile tests

* feat(profile): actually test clipboard copy

Use a mock clipboard in order to determine if the copy button actually
copies text into the clipboard.  Thank you to krachtstefan for their
mockClipboardAPI implementation:
microsoft/playwright#13037 (comment)

* feat(quick-links): add quick-links tests

* feat(quote): add quote tests

* feat(spotlight-landscape): add spotlight-landscape tests

* feat(spotlight-portrait): add spotlight-portrait tests

* feat(tabs): add tab tests

* feat(text): add text tests

* feat(video): add video tests

* feat(view): add view tests minus pagination

* feat(wrapped-image): add wrapped-image tests

* feat(link-treatments): add link treatment tests

* chore(pre-build-form): rename to pre-built-form

* chore(YSP-315): add screenshot on failures

* chore(YSP-315): finish moving search

* feat(search): test search for profiles

In our last release, we found that profiles were not being indexed for
search.  This ensures that we can test that profiles are being indexed
going forward.

* feat(comparison): compare visreg on ratio

Compare success of pages based on pixel ratio over pixels.  In this last
release test, the addition of link treatments on the page caused false
positives.  This gives enough leeway to allow variations while still
identifying big issues.

* feat(npm): add shortcut scripts

You can now use:
  - Test: npm run test
  - Run tests in UI: npm run ui
  - Run tests in debug mode: npm run debug

If you're making tests, and you prefer command line reporting, you can
use: npm run dev

The other scripts will use HTML as their reporter output.

* feat(playwright): default back to html reporter

* docs(README): update with new execution examples

* feat(directory): add email test

The email in a directory is now labelled "Email", and is a link with a
mailto to their entered email address.  This tests against that.

* feat(YSP-315): add newly released snapshots

This is done so that we can easily compare on next release.  This is a
capture of any pages that have changed since release so we can visually
regression test them next time.

* chore(YSP-315): temporarily skip keyboard tests

Until YSP-352 can be fixed, tabs will be unreliable.  For now, we're
inserting a test skip with the intention of re-enabling them once
YSP-352 is complete and work starts on YSP-378: Create E2E keyboard
tests for components.

* fix(YSP-315): fix tests after release

* fix(YSP-315): grand hero videos should autoplay

* fix(YSP-315): look for button based on regex

On my system, firefox auto plays the video for the grand hero.  On
Safari, Chromium, and Mobile Safari, it does not.  As such, the button
identifier actually changes based on the state of the video playing.
This uses a regex in order to capture either since we are only concerned
with whether the button exists and is showing, not what it says
necessarily yet.

* docs(YSP-315): add browser download instructions
@RuanAlesi
Copy link

RuanAlesi commented Mar 27, 2024

Same thing here

Microsoft.Playwright.PlaywrightException : Unknown permission: clipboard-write

Any news?

@amrsa1
Copy link
Author

amrsa1 commented Mar 27, 2024

I have found that we dont need to have this permission with webkit.

So simply this issue can be resolved as a work around by adding to projects one with chrome and relative permission and another project with webkit without permission

@RuanAlesi
Copy link

What do you mean don't need to have this permission @amrsa1 ?
Copying content into the application is one of my tests and using Webkit ends up with the error message:
The request is not allowed by the user or the platform in the current context, possibly because the user denied permission

@amrsa1
Copy link
Author

amrsa1 commented Mar 27, 2024

You dont need to have this permission with webkit.

So simply this issue can be resolved as a work around by adding to projects one with chrome and relative permission and another project with webkit without permission

I mean you can copy without permission as far as i remeber for webkit.

@RuanAlesi
Copy link

It's not what I see. I have that error message when using clipboard functions with Webkit.

@amrsa1
Copy link
Author

amrsa1 commented Mar 27, 2024

It's not what I see. I have that error message when using clipboard functions with Webkit.

The issue is that this permissions are dedicated for chrome.

If this test is running against multiple browser, maybe you can disable it for safari.

This ticket is there since long ago and i cant remeber how i over come this

@StevenBoutcher
Copy link

launchOptions: {
firefoxUserPrefs: {
'dom.events.asyncClipboard.readText': true,
'dom.events.testing.asyncClipboard': true,
},
}

This worked for me. I'll cite this in my blog post, thank you!

sergei-maertens added a commit to open-formulieren/open-forms that referenced this issue Jul 12, 2024
sergei-maertens added a commit to open-formulieren/open-forms that referenced this issue Jul 12, 2024
sergei-maertens added a commit to open-formulieren/open-forms that referenced this issue Jul 12, 2024
sergei-maertens added a commit to open-formulieren/open-forms that referenced this issue Jul 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests