我在使用接收base64編碼擴展文件列表的「extensions」參數做這件事時有點成功。
Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Apple iPhone 6");
Map<String, Object> chromeOptions = new HashMap<>();
chromeOptions.put("mobileEmulation", mobileEmulation);
try {
chromeOptions.put("extensions", singletonList(Base64.encode(FileUtils.readFileToByteArray(new File(WebDriverManager
.class.getResource("/extension_2_1_0.crx").toURI())))));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
driver = new ChromeDriver(capabilities);
// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/icon.png");
// setup ModHeader with headers
driver.executeScript(
"localStorage.setItem('profiles', JSON.stringify([{ " +
" title: 'Selenium', hideComment: true, appendMode: '', " +
" headers: [ " +
" {enabled: true, name: 'headerName', value: 'headerValue', comment: ''}, " +
" ], " +
" respHeaders: [], " +
" filters: [] " +
"}])); ");
return driver;