简体   繁体   中英

How do I simulate jquery events to trigger Google Autocomplete?

I want to use jquery to programmatically enter a word or phrase and then trigger the Google search box autocomplete suggestions from my console.

Here is what I have tried so far:

// Inject JQuery into page from console
var script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
document.body.appendChild(script);

// Add the word DOG into the search box
//** This part works **
$('input[name="q"]').val("dog");

// Attempt #1 to simulate clicking on the box
// ** This did appear to add a focus look to the box but it did not trigger the autocomplete suggestions listing
$('input[name="q"]').trigger("click");

// Attempt #2 to simulate clicking on the box
// ** This did not work.
$('input[name="q"]').trigger("mouseup");

If I go through the first part programmatically of injected jquery and then entering the word dog it works perfectly. I can even manually click on the search box and I will see all the search suggestions for the word dog even though I did not enter it manually. The issue is I can't seem to figure out via jquery how to programmatically simulate the proper event that results in it displaying the autosuggest as when I click manually.

Special thanks to sideroxylon for the reference. For anyone intersted here is how I got it to work.

// Inject JQuery into page from console var script = document.createElement("script"); script.src = "https://code.jquery.com/jquery-2.1.4.min.js"; document.body.appendChild(script);

// Add the word DOG into the search box //** This part works ** let searchbar = $('input[name="q"]');

searchbar.val('cat');

searchbar.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM