Automate a button click on chrome://extensions page using selenium webdriver - selenium

I'm trying to write an automated test that will automate the process of updating a google chrome extension. I'm not aware of another method of doing this automatically so here is what I'm currently trying to do:
Open the chrome extensions page (as far as I'm aware this is just an html page unless I'm missing something).
Click on the "Update extensions" button
Here is what I have tried having opened the chrome extensions page:
IwebElement UpdateButton = driver.findelement(By.Id("update-extensions-now"));
UpdateButton.Click();
For some reason the button click is not registering. I have tried some other locators such as CSS path and Xpath but they don't work either. Also, when I debug this test, it passes fine so I know it's not an issue with any of my locators. I have (as a test) tried to automate clicks on the other elements on this page and it's the same issue. I can't get a handle on any elements on the chrome://extensions page at all.
Has anyone encountered this or have any ideas as to what's going on?

You can use the Chrome extensions API to auto-update required extension.
Find the file "manifest.json" in the default Google Chrome
C:\Users\*UserName*\AppData\Local\Google\Chrome\User Data\Default\Extensions
There find the update URL of your extension:
{
"name": "My extension",
...
"update_url": "http://myhost.com/mytestextension/updates.xml",
...
}
The returned XML by the Google server looks like:
<?xml version='1.0' encoding='UTF-8'?>
<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>
<app appid='yourAppID'>
<updatecheck codebase='http://myhost.com/mytestextension/mte_v2.crx' version='2.0' />
</app>
</gupdate>
appid
The extension or app ID, generated based on a hash of the public key, as described in Packaging. You can find the ID of an extension or Chrome App by going to the Extensions page (chrome://extensions).
codebase
A URL to the .crx file.
version
Used by the client to determine whether it should download the .crx file specified by codebase. It should match the value of "version" in the .crx file's manifest.json file.
The update manifest XML file may contain information about multiple extensions by including multiple elements.
Another option is to use the --extensions-update-frequency command-line flag to set a more frequent interval in seconds. For example, to make checks run every 45 seconds, run Google Chrome like this:
chrome.exe --extensions-update-frequency=45
Note that this affects checks for all installed extensions and apps, so consider the bandwidth and server load implications of this. You may want to temporarily uninstall all but the one you are testing with, and should not run with this option turned on during normal browser usage.
The request to update each individual extension would be:
http://test.com/extension_updates.php?x=id%3DyourAppID%26v%3D1.1
You can find even more detailed information on exntesions developers site: https://developer.chrome.com/extensions

If you look at the HTML of the "chrome://extensions" page you will notice that the "Update extensions now" button is contained within an iframe. You need to switch to the iframe before trying to register a button click. i.e:
(This is in c#. Note that this code is written from memory so it may not be 100% accurate. Also, you will want to write more robust method. This code just quickly demonstrates that by switching to the iframe, it will work ok)
String ChromeExtensionsPage = "chrome://extensions";
driver.Navigate().GoToUrl(ChromeExtensionsPage);
driver.Switchto().Frame("DesiredFrame");
IwebElement UpdateButton = driver.findelement(By.Id("DesiredButtonID"));
UpdateButton.Click();

Related

Can vscode's markdown preview scripts trigger actions directly in an extension?

I'm writing a vscode extension where I'm hoping to squeeze more dynamic functionality out of markdown preview. Effectively the problem I'm trying to solve is:
In markdown preview, there's a checkbox
When user clicks the checkbox in markdown preview, send a message/event to the vscode extension runtime
Vscode extension can listen for this message/event and store the action in local storage
Checkbox state is saved - and subsequent renders of the markdown preview can use this action
Ideally, I'd like to do this while keeping the default markdown preview security (https://code.visualstudio.com/Docs/languages/markdown#_strict). After all, I don't need the extension to or markdown preview script to talk to a remote server - I just want them to be able to talk to one another.
Problem as code
To write the problem as sudo code, I want my markdown preview script to contain something like:
const button = ... // get button element
button.addEventListener('click', () => {
... /*
* Send a message to the vscode extension. Something like:
* `vscode.postMessage('vscode.my-extension.preview-action' + value)`
* (which I can't get to work, I'll discuss why)
*/
});
where then my extension can listen for messages like 'vscode.my-extension.preview-action'.
What I've Tried Already
I have tried acquireVsCodeApi() but because the markdown extension already does that, I can't do it again in the subsequent loaded script. I've also tried registering a uri handler but as far as I can try out the preview script still needs to fetch to that uri, which is still blocked by the default markdown security settings.
Perhaps markdown preview scripts are not the place to do this kind of thing, but I just wanted to leverage as much as possible that's already there with the vscode markdown extension. I want to supplement markdown but not replace it, the functionality I want to add is just icing on markdown documentation.
I've read https://code.visualstudio.com/api/extension-guides/markdown-extension#adding-advanced-functionality-with-scripts and it doesn't tell me much about markdown extension scripts capabilities and limitations.
Thanks to #LexLi I looked at some of the source code in the markdown extension and was able to come up with an ugly hack to make this work in preview scripts. Markdown allows normal clicks. And vscode extensions can handle normal clicks. I've paraphrased the code so there could be small syntax errors.
In the extension I did this:
vscode.window.registerUriHandler({
handleUri(uri: vscode.Uri): vscode.ProviderResult<void> {
console.log(`EXTENSION GOT URL: ${uri.toString()}`);
},
});
Then I made sure my extension/preview script put this in the document
<!-- in the preview script I place a button like this -->
<!-- it even works with hidden :) so I can do more app customization -->
<a
hidden
id="my-extension-messager"
href="vscode://publisher-id.my-extension"
>
cant see me but I'm there
</a>
Then my preview script I can even set href before faking a click:
const aMessager = document.querySelector("#my-extension-messager");
console.log('client is setting attribute and clicking...')
aMessager.setAttribute('href', 'vscode://publisher-id.my-extension?action=do-something');
aMessager.click();
console.log('client clicked');
Logs I saw (trimmed/tweaked from my particular extension to match the contrived example):
client is setting attribute and clicking...
client clicked
[Extension Host] EXTENSION GOT URL: vscode://publisher-id.my-extension?action%3Ddo-something
It's a hack but I can do a lot with this. Within the URL I can encode data back to the extension and kind of pass whatever I want (as long as data is relatively small).

Appium/WinAppDriver Can't Find Context Menu - But Only On Certain Machines

I'm running a set of automated UI tests using Appium/Winappdriver on Windows 10. The test framework is compiled in Visual Studio 2017 using mstest.
The problem that I am having is with tests that use a right-click to open a context menu, then select an element from the resulting menu. Locally, it works. It also works on our remote CI/CD machine. However, it does not work for the other two developers on the project, and we've spent two business days fruitlessly trying to figure out why.
We have the same Windows version (Windows 10, version 1903), we have the same Visual Studio 2017 (we also tried it with 2019, no luck), we have the same monitor resolution (1920 x 1080), we are targeting the same .NET framework (4.72), we have the same WinAppDriver, etc.
Everything else works just fine. But when the UI Test reaches that context menu, the test fails with the error "An element could not be located on the page using the given search parameters."
I used the WinAppDriver UI Recorder to find the XPath for the element. We also used it on the other user's machine and confirmed that, as far as the UI Recorder is concerned, the path is identical on both machines.
The specific call that fails:
Session.FindElementByXPath("/Pane[#ClassName=\"#32769\"][#Name=\"Desktop 1\"]/Menu[#ClassName=\"#32768\"][#Name=\"Context\"]/MenuItem[#Name=\"" + itemName + "\"]");
The WinAppDriver call on my machine (success):
{"using":"xpath","value":"/Pane[#ClassName=\"#32769\"][#Name=\"Desktop 1\"]/Menu[#ClassName=\"#32768\"][#Name=\"Context\"]/MenuItem[#Name=\"New Location\"]"}
HTTP/1.1 200 OK
Content-Length: 125
Content-Type: application/json
{"sessionId":"8970FDC1-E869-4304-A87D-D8F2CB711EA2","status":0,"value":{"ELEMENT":"42.856234.4.-2147483646.8140.18614751.1"}}
and the same call on the other user's machine (fail):
{"using":"xpath","value":"/Pane[#ClassName=\"#32769\"][#Name=\"Desktop 1\"]/Menu[#ClassName=\"#32768\"][#Name=\"Context\"]/MenuItem[#Name=\"New Location\"]"}
HTTP/1.1 404 Not Found
Content-Length: 139
Content-Type: application/json
{"status":7,"value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters."}}
Again, everything else works. Other UI tests that don't use the right-click context menus work just fine. It's only this particular area that fails.
What I've tried so far:
Using Thread.Sleep to force a long wait before making the call
Wrapping the call with a DefaultWait and polling it over a period of several seconds to see if the element becomes available during that time.
When the "An element could not be located" is thrown, retry up to a set number of times to find the element.
Lots and lots of double-checking to make sure we're both on the same version of the code, same libraries, same nuget packages, etc.
Trying a much broader locator ( Session.FindElementByName(itemName); )
The biggest head-scratcher is that when we check with UI Recorder, the element is there. When we check on my machine or the remote build machine, WinAppDriver can find it normally. But for some reason WinAppDriver can't find it on my coworker's machines.
This is a peculiar issue indeed.
I'd like to rule out the XPath selector as a potential problem here. Based on your syntax, it looks like you are using an absolute XPath. These can be extremely brittle depending on the circumstances. Not saying it's the root problem, but I would like to try a different selector to rule this out.
{"using":"xpath","value":"//MenuItem[#Name=\"New Location\"]"}
Using relative // notation tells your path to look anywhere on the page, rather than following a specific path down to the element itself.
Give this a try, and let me know if it helps at all.
For my application context menu is listed out of the DOM of actual application in inspect.exe. So switching back to desktop session after selecting the context menu worked fine for me.
var regressionChannelRow = labelProcessorSession.FindElementByName("5000");
Actions action1 = new Actions(labelProcessorSession);
regressionChannelRow.Click();
action1.ContextClick(regressionChannelRow).Perform();
Now creating a desktop session to get the "Stop" option from the context menu
AppiumOptions appCapabilities = new AppiumOptions();
appCapabilities.AddAdditionalCapability("app", "Root");
WindowsDriver<WindowsElement> desktopSession;
desktopSession = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), appCapabilities);
below is the context menu option which I need to select, remember to use desktop session here
var stopService = desktopSession.FindElementByName("Stop");
stopService.Click();
I've just replicated this issue. I was working on a test that I wrote last week, which was now getting stuck trying to find the context menu from a desktop session. I tried using various XPaths, searching by class name or just name, but it didn't seem to make any difference.
Eventually I tried closing Spotify, and that solved the issue! If you're experiencing this problem then try closing every application window possible.

Mime Type for adding sauce labs video link in cucumber report

I am trying to add a video link to the cucumber report using embedded method in scenario ,
String html = "www.saucelabs.com/asdfs234234sdafs/video.mp4";
scenario.embed(html.getBytes(), "text/html");
In the report i still see as text , not a link , also tried below , now this opening in windows media player instead of in browser
String html = "https://www.saucelabs.com/asdfs234234sdafs/video.mp4" >VideoLink;
scenario.embed(html.getBytes(), "text/html");
Can you please help me ? i want a link to appeared in the report by clicking upon , it must navigate to the sauce labs link.
Thanks in advance.
Ruby Implementation: (You can use the same logic in other languages too).
Just call this below line in your hooks.rb, before closing the driver. The below line of code will build the saucelabs video link dynamically based on driver session id.
puts "<button style=\"background-color: #525fa0;font-weight: bold;color: #fff;border: double;border-radius: 25px;\" onclick= \"window.open('https://saucelabs.com/jobs/#{browser.driver.session_id}','_blank')\">SauceLabs Execution Report</button>"
This will add a button to the html report with the saucelabs video link.
If you want to pass the url then use the below code.
puts "<button style=\"background-color: #525fa0;font-weight: bold;color: #fff;border: double;border-radius: 25px;\" onclick= \"window.open(url_goes_here,'_blank')\">SauceLabs Execution Report</button>"
If you are trying to access the html report from jenkins then make sure to run the below line in jenkins console.
System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "sandbox allow-scripts allow-popups unsafe-inline; ")
Make sure to restart the jenkins, once you ran the script in the script console.
This will allow you to see the report in the html otherwise your url will be blocked.

DuckDuckGo API - How to get more results?

The default search using the DuckDuckGo API returns only the results on the first page (around 25 I guess). Is there any way to get more results or navigate to the 2nd, 3rd pages of the search results?
Websites like Faroo have a parameter called s (which stands for start) which can be set to 1 if we want the first 10 results, to 11 if we want the next 10 results and so on. Is there something like that for DuckDuckGo, too?
According to DuckDuckGo Search API documentation, all the available parameters are:
q: query
format: output format (json or xml)
If format=='json', you can also pass:
callback: function to callback (JSONP format) pretty: 1 to make JSON
look pretty (like JSONView for Chrome/Firefox)
no_redirect: 1 to skip HTTP redirects (for !bang commands).
no_html: 1 to remove HTML from text, e.g. bold and italics.
skip_disambig: 1 to skip disambiguation (D) Type.
In particular, note that:
This API does not include all of our links, however. That is, it is
not a full search results API or a way to get DuckDuckGo results into
your applications beyond our instant answers.
TL/DR; - Install TamperMonkey, add the short script below (full instructions follow) and the browser will lazy-load the next page(s) automatically as you scroll.
After coming to this answer via Google and not finding the information I was seeking, I wrote this small TamperMonkey script to do the job. I post it here for future googlers.
The below userscript will work with Chrome, Firefox and Opera. Instructions for installation follow below the script, and a brief explanation of what TamperMonkey is follows below that.
This script is inspired by, and named similarly to (in honor of), Endless Google by Tumpio.
// ==UserScript==
// #name Endless DuckDuckGo
// #namespace http://tampermonkey.net/
// #match https://duckduckgo.com/?q=*
// #require http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js
// #grant none
// ==/UserScript==
(function() {
'use strict';
$(window).scroll(function(){
var els = document.querySelectorAll('.result.result--more');
if (els.length){
var elmore = document.querySelectorAll('.result--more__btn.btn.btn--full');
if (elmore.length){
elmore[0].click();
}
}
});
})(); //
How To Install the Above Script:
Install the TamperMonkey extension for Chrome (or the "add-in" for Firefox).
You will see the TamperMonkey icon appear at the top of the browser
Do a search on DuckDuckGo
Click on the TamperMonkey icon and from the drop-down menu, choose Dashboard
Along the tabs at the top of the Dashboard page, click on the [+] icon at left of the tab strip
The TamperMonkey editor will open up with a blank UserScript template. Delete that entire sample script and replace it with the script from this post.
Save [Ctrl] + [s]
Run another DuckDuckGo search and scroll down the page... True happiness is yours.
What Is TamperMonkey:
A good overview is here.
TamperMonkey is a browser extension, and there is a version of TamperMonkey for each major browser. You probably already use the AdBlock or uBlock browser extensions (if not, WHY NOT?), this is just another extension like those. Anyway, to install for Chrome or Brave, go to the Chrome Web Store and search for TamperMonkey by Jan Binoc. Install it. (Yes, it's safe - there are hundreds of thousands of users, mostly coders). Please consider donating - Jan deserves your support (and no, I don't know him, and yes I donated.)
Before TamperMonkey, there was another extension called GreaseMonkey that did the same thing but only worked on Firefox. However, the GreaseMonkey authors stopped maintaining it or something, and Jan Binoc stepped up to the plate with TamperMonkey.
TamperMonkey allows us to inject our own code into ANY webpage, to programmatically manipulate the web page on our local computers. How does that work? Simplistic Explanation: When you view a web page, you never actually view it "directly from the web server" - your browser first downloads a local copy of the web page code to your browser's cache folder and displays it to you from there. Therefore, TamperMonkey can intercept the page as it loads from cache (on your local hard drive) into the browser and modify it before it is displayed. That explanation is super-simplistic and not fully technically accurate, but in essence that is exactly how it works, and why TamperMonkey works. Most Importantly: The above few lines explain why the page does not change for anyone else - just for you, on your own computer.
TamperMonkey is an excellent reason to learn a bit of javascript/css/html. Using it, you can do stuff like hiding or re-arranging images on a webpage, removing clutter from a page, totally reformatting a page, etc. For example, one of my fav News sites has lots of clutter. So, I go to their RSS feed page, which acts like a great index of articles, but that also has too much stuff I don't want to see (mainly unnecessary thumbnail images and too-narrow columns). I wrote a short TM script to hide all the images and widen the columns and now, instead of seeing 5 or 6 article summaries per screen, I see ~ 20.
The absolute best, most concise, primer for html/css/js that I've ever seen is on Lynda.com. (You might already have access via your local library card - I was greatly surprised to find out that I do.) There is a series by Emma Saunders called D3.js Essential Training for Data Scientists. The course begins with two short tutorials (Recalling HTML Basics (4m) and Understanding HTML5 (3m) ) in html/css/js that are worth a university course tuition by themselves. Why can't everyone teach like this? Anyway, that's all you need - those first two (3 and 4 min) videos. Now, go tweak a webpage.
(Final disclaimer: No, I don't know Emma Saunders either, nor do I have anything to do with either Binoc's or Saunders' products in any way. I'm just a run-of-the-mill user and fan.)

Safari extension options pages with access to background page

I'm developing a cross-platform browser extension, and have based all my code on the Chrome-way of doing this. I have counted on that the background page will be accessible from the options page, which in Safari extensions turns out to be not possible (since there is no such thing as an options-page). You can only access safari.extension.globalPage.contentWindow from within the extension popup, and the background page itself.
Now, I have an options page, which is an html-page within the extension bundle, and so far I haven't found a way for Safari to give it extension "rights". The closest I have come is adding a content script that's only added on the options page. This seems a bit silly, since the html page itself is in the extension bundle?!
Others have suggested using asynchronous ping-pong style message event handlers, and even the canLoad-mechanism (which is "only" able to run in a beforeload-event). I have been able to hack the canLoad-mechanism for synchronous messaging by forging the BeforeLoadEvent:
// Content script (run from anywhere)
var result = safari.self.tab.canLoad(new BeforeLoadEvent, "data")
-> "return value"
// Background page
safari.application.addEventListener('message', function(e) {
if ( e.name === "canLoad" )
e.message = "return value";
}, true);
It's a hack, but it works. However, I am crippled by the message transport serialization, since I need to be able access methods and data on my objects from the background page. Is there anyway around this?
Possible ways that might work but I don't know if possible:
Access options-page window-object from backgrounds page. Is that possible?
Message passing, need to bypass message serialization
Any shared/global object that I can attach objects to and fetch from the options page?
Make Safari run the options.html page from outside the content-script sandbox? It works in Chrome since they are both within the extension-bundle. It's quite annoying that safari doesn't do this too.
Run the options-page from within the popup. This is promising, but it crashes safari (which is very promising!). However, from the looks of it it's just something to do with a CSS animation in my options.html page. The biggest issue is that it has to be able to open an OAuth2 popup, but thanks to being able to programmatically open the popover, it might be a non-issue. However, this option is the most realistic, but I would rather have it open in a new tab.
Any suggestions and hackish workarounds would really help.