niklasb / webkit-server

[not actively maintained] The C++ webkit-server from capybara-webkit with useful extensions and Python bindings
MIT License
48 stars 38 forks source link

check if element has focus #5

Closed Timmy000 closed 11 years ago

Timmy000 commented 11 years ago

Hi niklasb,

I ended up adding this set of functions to my local copy of webkit server.

Any chance you want to include them (or something like them) in the main repo?

diff --git a/src/capybara.js b/src/capybara.js
index da99a06..ba29ad9 100644
--- a/src/capybara.js
+++ b/src/capybara.js
@@ -135,6 +135,16 @@ Capybara = {
     return this.nodes[index].selected;
   },

+
+  hasFocus: function (index) {
+    var element = this.nodes[index];
+    return element == document.activeElement;
+  },
+
+  setFocus: function (index) {
+    document.activeElement = this.nodes[index];
+  },
+
   value: function(index) {
     return this.nodes[index].value;
   },
diff --git a/webkit_server.py b/webkit_server.py
index dd65f4c..e2c722f 100644
--- a/webkit_server.py
+++ b/webkit_server.py
@@ -171,6 +171,13 @@ class Node(SelectionMixin):
     """ is this node a multi-select? """
     return self.tag_name() == "select" and self.get_bool_attr("multiple")

+  def has_focus(self):
+    """ does this node have focus """
+    return self._invoke("hasFocus") == "true"
+
+  def set_focus(self):
+    return self._invoke("setFocus")
+
   def _get_xpath_ids(self, xpath):
     """ Implements a mechanism to get a list of node IDs for an relative XPath
     query. """
niklasb commented 11 years ago

Hi Timmy,

while this is definitely a useful addition, I am hesitant to diverge even more from the original server. In general, I don't really like the idea of the capybara.js file, which is hardcoded into the server. A more flexible approach (which you can easily use without extending either the server or the dryscrape lib) would be:

def has_focus(node):
    return node.eval_script("node == document.activeElement")

def set_focus(node):
    node.exec_script("document.activeElement = node")
Timmy000 commented 11 years ago

Fair enough, I'll use the snippet you've suggested.