ランダム検索アプリ
何かキーワードを入力してください。
ご要望いただいたアプリケーションの実装例を以下に示します。このアプリは、ユーザーが入力したキーワードでGoogle検索を行い、最初に見つかった検索結果のタイトルとURLを表示します。なお、このアプリではユーザーからの入力チェックやエラー処理を省略していますので、セキュリティ上の問題やバグ等にはご注意ください。
<!DOCTYPE html>
<html>
<head>
<title>ランダム検索アプリ</title>
<meta charset="UTF-8">
</head>
<body>
<h1>ランダム検索アプリ</h1>
<p>何かキーワードを入力してください。</p>
<input type="text" id="keyword">
<button onclick="search()">検索</button>
<div id="result"></div>
<script>
function search() {
let keyword = document.getElementById("keyword").value;
let url = 'https://www.google.com/search?q=' + encodeURIComponent(keyword);
fetch(url)
.then(response => response.text())
.then(html => {
let parser = new DOMParser();
let doc = parser.parseFromString(html, "text/html");
let title = doc.querySelectorAll("h3")[0].textContent;
let href = doc.querySelectorAll("a")[0].href;
document.getElementById("result").innerHTML = "<a href='" + href + "'>" + title + "</a>";
});
}
</script>
</body>
</html>
ジョーク:「面白いことを言おうと思ったけど、Google検索結果の一番上には『あなたの検索結果に基づいて、次の記事がおすすめです。』と書いてあったので諦めました。」