Wahaha2001
Wahaha2001

Reputation: 213

Any way to select a line of text in browser screen by webdriver to emulate keyboard or mouse?

I want to use WebDriver to select a line of text in browser screen(actually in CKEditor editing area) then change its text style from CKEditor toolbar. Any method can do that?

For example, a line with html code like below:

this is a sample line.

I try to use Actions to build a mouse action chain but no success due to not familiar with that. Thanks for any hints or answer.

Upvotes: 2

Views: 2586

Answers (2)

Martins Balodis
Martins Balodis

Reputation: 2068

You can also try to do it with JavaScript:

let el = document.querySelectorAll("p")[0];
let range = document.createRange();
range.selectNodeContents(el);
window.getSelection().addRange(range);

Upvotes: 0

Mike Kwan
Mike Kwan

Reputation: 24457

I'm not sure this is actually possible with WebDriver. What you would want to do is to clickAndHold(...).moveByOffset(...).release(...). Unforunately, WebDriver only allows a WebElement as a parameter to clickAndHold().

My best advice to you is to emulate JavaScript events for this. You can then do something like this in your test:

((JavascriptExecutor) driver).executeScript(...);

I wrote code for emulating mouse events which I use with some of my Selenium tests. Although it doesn't do exactly what you want, hopefully it will be useful (hopefully you can just set the x/y coords and perhaps that will get it working):

var f = function() {
  var id  = "ext-gen1116";
  var top = document.querySelector( '#ext-gen1116:nthchild(0)' );
  var bot = document.getElementById( id ).childNodes[3];

  var getX = function( obj ) {
    if( obj == null ) {
      return 0;
    } else {
      return obj.offsetLeft + getX( obj.offsetParent );
    }
  }

  var getY = function( obj ) {
    if( obj == null ) {
      return 0;
    } else {
      return obj.offsetTop + getY( obj.offsetParent );
    }
  }

  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("mousedown", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  bot.dispatchEvent(evt);

  evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("mousemove", true, true, window,
    0, 0, 0, getX( top ) - getX( bot ), getY( top ) - getY( bot ),
    false, false, false, false, 0, null);
  bot.dispatchEvent(evt);

  var mouseup = function( elem ) {
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("mouseup", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
    elem.dispatchEvent(evt);
  }

  setTimeout( mouseup, 500, bot );
};
f();

If it's possible for you to do what you want with the keyboard instead, this is by far the better solution. You can simply do driver.sendKeys(...). The Keys enum will be priceless for you in this case :-)

Upvotes: 1

Related Questions