Search code examples
selenium-webdriverselenium-chromedriverclipboard

How can I allow copy/paste in Selenium while running in localhost?


I'm using Selenium with ChromeDriver to run tests on my website. I run them in localhost. Some of my tests activate elements on the page that utilize the clipboard api. This pops up a box asking for permission. I need to somehow bypasss this box and allow the browser to access the clipboard without user intervention. I tried every single option I can find on the web, but they are simply ignored. Except for the last 2 lines, which are not ignored but cause an error.

Here are all my (so far unsuccessful) attempts:

        var opts = new ChromeOptions();
        opts.AddArgument("start-maximized");
        //opts.AddUserProfilePreference("profile.default_content_settings.popups", 0);
        //opts.AddUserProfilePreference("profile.default_content_settings.notifications", 1);
        //opts.AddUserProfilePreference("profile.default_content_setting_values.notifications", 1);
        //opts.AddUserProfilePreference("profile.default_content_setting_values.clipboard-read", 1);
        //opts.AddUserProfilePreference("profile.default_content_setting_values.clipboard-write", 1);
        //opts.AddUserProfilePreference("profile.content_settings.exceptions.clipboard", "*={'setting': 1}");
        var chrm = new ChromeDriver("D:\\Projects\\General", opts);
        //chrm.SetPermission("clipboard-read", "granted");
        //chrm.SetPermission("clipboard-write", "granted");
        driver = chrm;

The error I get from using SetPermission is:

OneTimeSetUp: OpenQA.Selenium.WebDriverArgumentException : invalid argument: Permission can't be granted to opaque origins. (Session info: chrome=119.0.6045.105)

From my understanding, localhost is an opaque origin.

How can I bypass this access alert?

Thanks in advance


Solution

  • Try this code:

    var clipboardException = new Dictionary<string, object> {{"[*.],*",new 
    Dictionary<string, object> {{"last_modified", 
    DateTimeOffset.Now.ToUnixTimeMilliseconds()},{"setting", 1}}}};
    var opts = new ChromeOptions();
    opts.AddArgument("start-maximized");
    opts.AddUserProfilePreference("profile.content_settings.exceptions.clipboard", clipboardException);
    var chrm = new ChromeDriver("D:\\Projects\\General", opts);