1

A website is displaying a lot of items in a table. The table changes as I type into the searchbar at the top, which acts as a filter. This should be automated (client-sided).

I created a Chrome extension to run the script.

The problem:
My script is able to set the searchbar's value to the string that i want it to be using:

document.getElementById('filter').value = "Apple";

The problem is, that the table below is not being updated even though the text inside the searchbar is displaying "apples". If i remove a letter by hand, it instantly updates and filters the results.

Is there any way to "simulate" actual keypresses so the table gets updated?


Edit and almost solution:

I have been trying so hard to make this work and failed every single time. Then I started to learn a bit of jquery and came over this. A single line of code.

$("#filter").val("apple").trigger('keyup');

Works perfectly fine.

I still thank you a lot, marcelino! You've been a big help and you tried so hard to solve my problem with me! Thank you!

Edit_2 and final solution:

The first "solution" didn't work when using it in a chrome extension. This solution works perfectly fine. It changes the value and then fires an ArrowUp event to trigger the filter.

var filter = document.getElementById("filter");
filter.value = "apple";
filter.dispatchEvent(new KeyboardEvent("keyup", {
    bubbles: true,
    cancelable: true,
    key: "ArrowUp"
  }));

Solved here: Different results between chrome console and extension

Community
  • 1
  • 1
Thomas Weiss
  • 375
  • 1
  • 2
  • 16
  • From my understanding it is not the same. I would also need to somehow "activate" the textfield to simulate a keypres inside of it. I am new to javascript, so i need some help here! Even if I already visited this link, thank you! – Thomas Weiss Jun 04 '16 at 15:00
  • No problem, Thomas. Check my answer below, if it doesn't address your needs, please comment there. – m-a-r-c-e-l-i-n-o Jun 04 '16 at 15:07

1 Answers1

3

You could simulate keypresses by doing:

// more info about keypress simulation at:
// http://stackoverflow.com/a/5920206/1666547
// you don't have to understand how this part works
// just know that it makes the method "document.triggerKeyPress" 
// available for us to use to simulate keypresses
// put this somewhere at the beginning of your script
//Node.prototype.triggerKeyPress = function(char) {
//    var event = document.createEvent('Event');
//    event.initEvent('keyup', true, true);
//    event.keyCode = char.charCodeAt(0);
//    document.dispatchEvent(event);
//}

// this second part you should try your best to understand
// grab the filter element from the D.O.M.
var $filterElement = $('#filter')//document.getElementById('filter')
// set a value to the filter element if you need to
$filterElement.val('Apple')
// focus the cursor on it for typing
$filterElement.focus()
// grab the value from the filter input
// lets say that the "queryInput" is "Apple"
var queryInput = $filterElement.val()
// listen to the event
//window.addEventListener('keyup', function(event) {
  // var actualCharacter = String.fromCharCode(event.keyCode)
  // console.log('Typed:', actualCharacter)
//})

$filterElement.keyup(function (event) {
  var actualCharacter = String.fromCharCode(event.which)
  console.log('Typed:', actualCharacter)
})
// now we are going to iterate through each character of "queryInput"
// and fire a "keyup" event for each character so that table filter
// thinks that someone actually typed the word "Apple" and filters
// accordingly. 
queryInput
.split('') // make string into an array by splitting it on empty spaces
.forEach(function(letter) { // iterate over the characters "A-p-p-l-e"
  // using the "document.fire" method we created above
  var e = jQuery.Event('keyup');
  e.keyCode = letter.charCodeAt(0);
  e.which = letter.charCodeAt(0); // # Some key code value
  $filterElement.trigger(e);
  //document.triggerKeyPress(letter) // fire the "keypress" event
})
<input id="filter" type="text" name="fname">
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

I hope that helps.

m-a-r-c-e-l-i-n-o
  • 2,622
  • 18
  • 26
  • Hey, it might eventually fit my needs, but I feel like this is too advanced for my knowledge in JS and I am not sure how to use it properly. I also checked the link at the top. My script is supposed to run by itself, so after opening the website, the input with the id "filter" has to be actived automatically and filled with "apple" in a way, that the website recoginizes it and updates the table below. After that my script needs to grab some elements that only appear when the page is being filtered. Could you give me a hint on how to use this piece of code? How can I use it for my case? – Thomas Weiss Jun 04 '16 at 15:15
  • I just edited my answer with a step by step explanation of the code. It's hard to say more without looking at all the code you've written, but take a look at the comments, understand it, and try to adapt it to your needs. Based on your post, all the pieces u need should be there. – m-a-r-c-e-l-i-n-o Jun 04 '16 at 15:41
  • Hey and thanks a lot for the work here! Sadly, the only thing that happens when I run that script is "VM470:25 Uncaught ReferenceError: letter is not defined(…)". If i try something like "document.getElementById('filter').focus();", nothing happens. It seems like it can't focus the input field even though I think I understood what this whole thing does. – Thomas Weiss Jun 04 '16 at 16:06
  • Sorry about that, honest mistake on the "ReferenceError: letter is not defined", fixed and also had to substitute the keypress simulation. I made the working code into a snippet so that you can see it in action. When you press "Run code snippet", notice how there is a blinking cursor on the input field. – m-a-r-c-e-l-i-n-o Jun 04 '16 at 16:54
  • Okay, it focuses the searchbar and successfully types the string, but the table doesn't refresh until i hit a key (doesn't matter if it`s a letter or for example an arrow key). This is weird... – Thomas Weiss Jun 04 '16 at 18:32
  • What table filtering system are you using? Can you post the code? Maybe it's listening to an event other than "keydown". It could be "keyup", "keypress", "input", or maybe even "change" (although these last two are unlikely in this case). – m-a-r-c-e-l-i-n-o Jun 04 '16 at 20:08
  • It's not my website. I am just trying to automate some stuff there. How can I find that out? – Thomas Weiss Jun 04 '16 at 20:25
  • Does this help? " $('#filter').on('keyup', function () {" - found it in the 'inventory.js' i found from chrome's sources console. http://pastebin.com/Ub7C7sV6 – Thomas Weiss Jun 04 '16 at 20:42
  • Try the code above, I edited it to simulate the "keyup" event instead of "keydown". – m-a-r-c-e-l-i-n-o Jun 05 '16 at 00:25
  • Still the same result. Doesn't update. Thanks again for the try! – Thomas Weiss Jun 05 '16 at 01:21
  • Wait, before you give up, try the code from this one last edit I just made. I did the keyup simulation with jQuery, which could make a difference since in your script, jQuery is used to set the event. – m-a-r-c-e-l-i-n-o Jun 05 '16 at 01:50
  • 1
    And nope...same result again. Thank you so so much for all of your help! If I can find any further information, I can revive this one here if you want to! – Thomas Weiss Jun 05 '16 at 01:59
  • Awesome! Thanks for coming back and updating me on this! Very happy you figured it out :] – m-a-r-c-e-l-i-n-o Jun 11 '16 at 14:32
  • Sadly it only works from the chrome console, somehow not from the extension. Need to keep trying... – Thomas Weiss Jun 11 '16 at 14:34
  • :) Would you happen to know why the "ArrowUp" is necessary? – m-a-r-c-e-l-i-n-o Jun 12 '16 at 17:38
  • I dont know. :D Just used a key that doesnt change the input so I can set the value and then just trigger the event by pressing a random key. – Thomas Weiss Jun 12 '16 at 17:40