masterdevs / chromedevtools Goto Github PK
View Code? Open in Web Editor NEW.NET library to interact with the Chrome Debugger
License: MIT License
.NET library to interact with the Chrome Debugger
License: MIT License
HI ,
Just downloaded release 1.1.0 and tried to build, and got below error
Unable to find version '1.0.3' of package 'CoolWhip'. MasterDevs.ChromeDevTools
please help
thank you
Dheeraj Kumar
Hi
I know that this question is not directly related to this project but I hope I can find here answer to my question.
I was able to invoke Chrome Remote Interface functions inside Selenium WebDriver session (Page.captureScreenshot, Emulation.clearDeviceMetricsOverride etc). But I have problem with invoking methods which work on DOM element. The problem is with nodeId parameter. For example this function https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-setFileInputFiles accepts as one of parameters nodeId. I can't figure out how to extract nodeId based on IWebElement from SeleniumWebdriver.
How can I find nodeId using Selenium or Javascript?
Hi,
I'm trying to run a test - following the sample program.
When I run the app, I get this error below:
Additional information: Don't know what to do with response:
{"method":"Page.lifecycleEvent","params":{"name":"DOMContentLoaded","timestamp":160473.321307}}
I am at a loss as to what to do with it!
Do you have any information that will help me to sort this out ?
Thanks,
Richard
When using the ChromeSession
class with Android devices, I've stumbled upon a couple of improvements which can be made. I haven't had the time yet to backport those changes to ChromeDevTools, but wanted to share them here just in case:
EnsureInit
calls Init.Wait()
. You can make EnsureInit
async by using a SemaphoreSlim
instead of a lock to protect the _webSocket
field; SemaphoreSlim
has a WaitAsync
methodTask.Run
A couple of methods which wait for ManualResetEvent
classes use Task.Run
because ManualResetEvent.WaitOne
is a sync method. I've used Nito.AsyncEx, which has an AsyncManualResetEvent
, which has an async wait methodWaitOne
methods. When using the async variant, you can await the MRE & a Delay task, implementing a kind of time-out mechanism.EnsureInit
checks for _webSocket
being null, but it does not account for scenarios where the socket was closed. We're not quite sure yet why we end up with closed sockets from time to time (we believe it may be a server-side timeout), but having EnsureInit
check for a closed socket & reopen the socket in that case worked for usIf I find the time 😄 , I'll try to create a PR for this, in meanwhile, already wanted to share this, may be useful for others.
Hi!
I was trying, unsuccessfully, to load an url and check the cookies loaded:
chromeSession.SendAsync(new NavigateCommand
{
Url = "http://www.google.com/"
});
ICommandResponse result =chromeSession.SendAsync(new GetCookiesCommand
{
}).Result;
Please could you explain briefly how to send command properly and how to recover results?
Thanks in advance for your effort and share your work!!!
Hi,
I have created a Chrome session using the WebSocketDebuggerUrl. I want to Know how to get the properties of class which does not extend ICommand.
Ex: I want to know the Properties like VersionId, RunningStatus, Satus of ServiceWorkerVersion class.
Task.Run(async () => { var chromeSessionFactory = new ChromeSessionFactory(); var chromeSession = chromeSessionFactory.Create(<url>); }).Wait();
Using chromeSession, any way to get the above details
Hello.
First I apprepriate this project very well.
I used this project for several months, and It did work very well.
But since yesterday, I have a error, and I can't use this ChromeDevtools project anymore.
I attach screenshot here.
This is image url.
When I try to send "SendCommand", I m faced on the error of Websocket_Error cause of HTTP/1.1 403 Forbidden.
Really strange...
PrintToPDFCommand hangs forever when printing to PDF
public static double cm2inch(double centimeters)
{
return centimeters * 0.393701;
}
PrintToPDFCommand printCommand = new PrintToPDFCommand()
{
MarginTop = 0,
MarginLeft = 0,
MarginRight = 0,
MarginBottom = 0,
PrintBackground = true,
Landscape = false,
PaperWidth = cm2inch(21),
PaperHeight = cm2inch(29.7)
};
System.Console.WriteLine("Printing PDF");
CommandResponse<PrintToPDFCommandResponse> pdf = await chromeSession.SendAsync(printCommand);
System.Console.WriteLine("PDF printed.");
byte[] pdfData = System.Convert.FromBase64String(pdf.Result.Data);
System.IO.File.WriteAllBytes("output.pdf", pdfData);
System.Console.WriteLine("PDF stored");
Could you please provide full "Hello world" example.
Thank you!
example: I'm unable to set session cookie.
protocol.json:
{ "name": "setCookie", "parameters": [ ..... { "name": "expirationDate", "$ref": "Timestamp", "optional": true, "description": "If omitted, the cookie becomes a session cookie." } ]...
(Timestamp is typedef for number)
resulting SetCookieCommand:
/// <summary> /// Gets or sets If omitted, the cookie becomes a session cookie. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public double ExpirationDate { get; set; }
^ double is not nullable thus the zero is sent instead of ommiting
Hi everybody,
I'm trying to retrieve data from a javascript function in an application running on Chromium v53. The function returns a promise which contains an object with the values I'm looking for. The problem I'm having is that I can't resolve the promise.
The following code works fine if I execute it directly in chrome:
var list = app.db.getTracklist('SELECT * FROM Songs', -1);
console.log(list.isLoaded); // returns false
console.log(list.asJSON); // returns blank data
list.whenLoaded().then(function(result){
console.log(result.isLoaded) //returns true
console.log(result.asJSON) // returns the data I want
})
What I want to do in my application is the following:
var cmd = new EvaluateCommand{
ObjectGroup = "console",
IncludeCommandLineAPI = true,
DoNotPauseOnExceptionsAndMuteConsole = false,
ReturnByValue = true,
Expression = "app.db.getTracklist('SELECT * FROM Songs', -1)"
};
var response = chromeSession.SendAsync(cmd).Result as CommandResponse<EvaluateCommandResponse>;
Console.WriteLine(response.Result.Result.Value);
The last line prints a json object which has the properties isLoaded and asJSON - which are false and blank, respectively. That makes sense since whenLoaded() needs to be called in order to load the data. If I change the expression of the call to "app.db.getTracklist('SELECT * FROM Songs', -1).whenLoaded()", SendAsync() returns a promise (as opposed to the object the promise returns). If I execute synchronous functions I get correct results, so I'm positive that the basic setup is fine.
Does anybody know what I need to do in order to get the data that would be returned in the then() block of the original function?
How to detect element when the mouse is moveover,and Highlight the element,when mouse click ,get the element attribute?
I want run "GetDocumentCommand",but the result is null.
//my test method
private static void Test()
{
try
{
string url = "ws://localhost:9222/devtools/page/66CB09FA-3637-4C41-A1D8-DC4A3EDE428D";//url is ok,point to a chrome process with debug port 9222.
ChromeSessionFactory sf = new ChromeSessionFactory();
IChromeSession chromeSession = sf.Create(url);
var x = chromeSession.SendAsync<GetDocumentCommand>().Result;
var y = x as CommandResponse<GetDocumentCommandResponse>;
//here ,y.Resut=null,y.Method=null。but y.Id has value.
WriteMessage(y.Result, "GetDocumentCommand=");
}
catch (Exception exp) { Console.WriteLine("exception="+exp.Message); }
Console.ReadKey();
}
I fix this , But I don't know why this happend, Is other where influence by this error?
my fix
1.open ChromeProcessFactory.cs
2. add some code into "Create" method as follow:
public ICommandResponse Create(string responseText)
{
var jObject = JObject.Parse(responseText);
if (null != jObject["error"])
{
return jObject.ToObject();
}
var methodString = GetMethod(jObject);
if (null == methodString)
{
return null;
}
var typeInferredFromMethod = _methodTypeMap.GetCommandResponse(methodString);
if (null == typeInferredFromMethod)
{
return null;
}
var genericEventType = typeof(CommandResponse<>);
var commandResponseType = genericEventType.MakeGenericType(typeInferredFromMethod);
var result = jObject.ToObject(commandResponseType);//here,don't know why: result.Result=null,result.Method=null
//new code begin
var cqs_r = jObject.GetValue("result");
var cqs_o = cqs_r.ToObject(typeInferredFromMethod);
commandResponseType.GetProperty("Result").SetValue(result, cqs_o);
commandResponseType.GetProperty("Method").SetValue(result, methodString);
//new code end
return result as ICommandResponse;
}
Netstandard nuget support is missing.
I can't understand how to inject a javascript code into the web page. Also how could I get a possible return from this script. I loaded the MasterDevs.ChromeDevTools Solution in C#.
Thanks
Is there a way to get ChromeDevTools to work in kiosk mode?
Hello I am trying to implement video recording for Selenium tests (headless Chrome)
I start Chrome with Selenium and get WebSocketDebuggerUrl from the driver log.
After this, I am trying to create ChromeSession object but it fails with NullReferenceException
I read entire ReadMe - and check sample - but it still not clear for me - should I Rebuild protocol or do smth else?
`var service = ChromeDriverService.CreateDefaultService();
service.LogPath = $"c:\temp\{Guid.NewGuid()}.log";
service.EnableVerboseLogging = true;
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
chromeOptions.AddArguments("window-size=2560,1440");
chromeOptions.AddArguments("no-sandbox");
Driver = new ChromeDriver(service, chromeOptions, _timeout);
var webSocketDebuggerUrl = string.Empty;
while (string.IsNullOrEmpty(webSocketDebuggerUrl))
{
try
{
using (var fs = new FileStream(service.LogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader reader = new StreamReader(fs))
{
while (!reader.EndOfStream)
{
//"webSocketDebuggerUrl": "ws://localhost:59941/devtools/browser/2ccd43e7-e96a-4432-9d0d-bc29e8f13c5b"
var line = reader.ReadLine();
if (line.Contains("webSocketDebuggerUrl"))
{
var split = line.Split(' ');
webSocketDebuggerUrl = split[split.Length - 1].Replace("\"", string.Empty);
}
}
}
}
}
catch
{
}
}
var chrome = Driver as ChromeDriver;
var parameters = new Dictionary<string, object>
{
{ "format", "png" },
{ "everyNthFrame", 1 }
};
chrome.ExecuteChromeCommand("Page.startScreencast", parameters);
var chromeSessionFactory = new ChromeSessionFactory();
var chromeSession = chromeSessionFactory.Create(webSocketDebuggerUrl);`
P.S.
Thx for this great repository!
多个标签页如何切换
Currently there are two separate projects, one for "Desktop" .NET and one for .NET Core. As a result, the build also outputs two separate NuGet packages.
We should try to unify that.
I have following code based on official sample of this project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using Task = System.Threading.Tasks.Task;
using System.Windows.Forms;
using MasterDevs.ChromeDevTools;
using DOM = MasterDevs.ChromeDevTools.Protocol.Chrome.DOM;
using Emulation = MasterDevs.ChromeDevTools.Protocol.Chrome.Emulation;
using Page = MasterDevs.ChromeDevTools.Protocol.Chrome.Page;
namespace FreelanceRuBot
{
class Program
{
const int ViewPortWidth = 1440;
const int ViewPortHeight = 900;
static void Main(string[] args)
{
Task.Run(async () =>
{
var getHTMLDone = new ManualResetEventSlim();
var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
using (var chromeProcess = chromeProcessFactory.Create(9222, true))
{
var sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault();
var chromeSessionFactory = new ChromeSessionFactory();
var chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);
await chromeSession.SendAsync(new Emulation.SetVisibleSizeCommand
{
Width = ViewPortWidth,
Height = ViewPortHeight
});
var navigateResponse = await chromeSession.SendAsync(new Page.NavigateCommand
{
Url = "http://www.google.com"
});
var pageEnableResult = await chromeSession.SendAsync<Page.EnableCommand>();
chromeSession.Subscribe<Page.LoadEventFiredEvent>(loadEventFired =>
{
Task.Run(async () =>
{
var doc = (await chromeSession.SendAsync(new DOM.GetDocumentCommand())).Result.Root;
var res = chromeSession.SendAsync(new DOM.GetOuterHTMLCommand());
getHTMLDone.Set();
});
});
getHTMLDone.Wait();
Console.WriteLine("Exiting ..");
}
}).Wait();
}
}
}
Some error occurs in this line;
var res = chromeSession.SendAsync(new DOM.GetOuterHTMLCommand());
But it is not issue about an error. It is issue about how to handle such errors.
This line hasn't any result processing, but anyway it crashes with: System.InvalidCastException. Place is ChromeSession.cs, CastTaskResult method, 94 line.
Because it can't cast "MasterDevs.ChromeDevTools.ErrorResponse" to "MasterDevs.ChromeDevTools.CommandResponse`.
I want to obtain ErrorResponse in such case. But it looks like there are no normal way to obtain it.
P. S. I could contribute if you will merge :)
As result of
await chromeSession.SendAsync(new SetExtraHTTPHeadersCommand { Headers = new Dictionary<string, string> { {"my_custom_header", "my_value"} } });
no extra header was sent.
Same request via nodejs works:
await Network.setExtraHTTPHeaders({ headers: { "my_custom_header": "my_value" } });
How can I collect coverage data using this API?
Thanks
I've added support for .NET 4.0.
Just 3 small changes necessary, and these additional files:
https://github.com/ststeiger/ChromeDevTools/tree/master/source/MasterDev.ChromeDevTools.DotNet4/Net4
Check if you want to integrate it.
Install-Package Microsoft.Bcl.Async
Install-Package Microsoft.Net.Http
and finished
Hi All
I got an Internal Server Error (500) for each await chromeSession.SendAsync()
I am using Nuget build (1.1.0)
Thanks
How to read the user profiles list ?
How to read opened URLs in that profile?
How to select a profile on browser startup?
As you may know the protocol.json file is now split into two different files, browser_protocol.json and js_protocol.json.
Would it be possible to add support for 1.2?
(Or did I miss something?)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.