Chrome ブラウザを HTML、CSS、JavaScript で作るというのは、実際には Chromium というオープンソースプロジェクトを基にしている Google Chrome を完全に再現するという意味ではなく、簡易的なブラウザの UI と基本的な機能を持った「ブラウザっぽいもの」を作るということと解釈します。ここでは、非常に基本的な機能のみを持つ簡易的なウェブブラウザを HTML、CSS、JavaScript で作成する例を示します。
HTML (index.html)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Browser</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="browser">
<div class="toolbar">
<input type="text" id="url-input" placeholder="URLを入力">
<button id="go-btn">Go</button>
<button id="back-btn">戻る</button>
<button id="forward-btn">進む</button>
</div>
<iframe id="webview" src="about:blank"></iframe>
</div>
<script src="script.js"></script>
</body>
</html>
CSS (style.css)
body, html {
height: 100%;
margin: 0;
padding: 0;
}
.browser {
display: flex;
flex-direction: column;
height: 100%;
}
.toolbar {
padding: 5px;
background-color: #f0f0f0;
border-bottom: 1px solid #ccc;
display: flex;
align-items: center;
}
#url-input {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
}
button {
margin-left: 5px;
padding: 10px;
font-size: 16px;
}
#webview {
flex-grow: 1;
border: none;
}
JavaScript (script.js)
document.addEventListener('DOMContentLoaded', function() {
const urlInput = document.getElementById('url-input');
const goBtn = document.getElementById('go-btn');
const backBtn = document.getElementById('back-btn');
const forwardBtn = document.getElementById('forward-btn');
const webview = document.getElementById('webview');
let history = [];
let currentIndex = -1;
goBtn.addEventListener('click', function() {
const url = urlInput.value;
if (!url.startsWith('http://') && !url.startsWith('https://')) {
urlInput.value = 'http://' + url;
}
navigate(urlInput.value);
});
backBtn.addEventListener('click', function() {
if (currentIndex > 0) {
currentIndex--;
urlInput.value = history[currentIndex];
webview.src = history[currentIndex];
}
});
forwardBtn.addEventListener('click', function() {
if (currentIndex < history.length - 1) {
currentIndex++;
urlInput.value = history[currentIndex];
webview.src = history[currentIndex];
}
});
function navigate(url) {
if (currentIndex < history.length - 1) {
history = history.slice(0, currentIndex + 1);
}
history.push(url);
currentIndex++;
urlInput.value = url;
webview.src = url;
}
});
このコードは、シンプルなウェブブラウザの UI と、ページの表示、戻る、進むの基本的なナビゲーション機能を提供します。ただし、これは本格的なブラウザではなく、セキュリティ機能や高度なレンダリング機能などは備えていません。
この例では、<iframe>要素を使用してウェブページを表示しています。入力された URL には、http:// または https:// が付いていない場合、http:// を自動的に付加します。また、簡易的な履歴管理機能により、「戻る」と「進む」ボタンを実装しています。
このコードを一つの HTML ファイルにまとめることは推奨しませんが、可能ではあります。具体的には、CSS を <style> タグ内に、JavaScript を <script> タグ内に記述します。
<!DOCTYPE html>
<html>
<head>
<!-- head 部分 -->
<style>
/* CSSをここに記述 */
</style>
</head>
<body>
<!-- body 部分 -->
<script>
// JavaScriptをここに記述
</script>
</body>
</html>
ただし、コードの管理や可読性の観点から、別々のファイルとして保持することをお勧めします。