1 回答

TA貢獻1818條經驗 獲得超11個贊
“他們從哪里獲得這些數據?”
通過查看擴展程序的源代碼,此 URL:
https://google.com/complete/search?client =firefox&hl=en&q=foo
它與 Google 在其搜索頁面上使用的 API 相同。但該 API 受CORS 策略保護,因此無法從任何網頁訪問。瀏覽器擴展可以,因為它被授予了更多權限。要使用它,您需要一臺代理服務器(可以是您自己的,也可以是免費的,如下例中的服務器)。
const searchInput = document.getElementById('search'),
? suggestionsList = document.getElementById('suggestions');
searchInput.addEventListener('input', autocomplete);
autocomplete();
function autocomplete() {
? const q = searchInput.value;
? const proxy = 'https://cors-everywhere.herokuapp.com/';
??
? fetch(`${proxy}https://google.com/complete/search?client=firefox&hl=en&q=${q}`, {
? ? headers: { origin: 'google.com' }
? })
? .then(res => res.json())
? .then(res => {
? ? suggestionsList.innerHTML = res[1].map(x => `<li>${x}</li>`).join('')
? });
}
<input id="search" value="foo" />
<ul id="suggestions"></ul>
添加回答
舉報