the following code is a scraping tool, but there is a bug in auto-fetch switch unable to read from cookie after changing (supposed to save to cookie) and refresh (suppose to load from cookie, set the value and deterimine whether to auto-fetch for)
can you remove all existing code related to auto-fetch and reimplemented the feature? hopefully to solve the bug:
code Copy code
h1 {
color: #333;
text-align: center;
width: 100%;
margin: 20px 0;
}
.table-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background-color: #e0e0e0;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
border-radius: 12px;
overflow: hidden;
}
th,
td {
padding: 12px;
text-align: left;
}
th {
background-color: #e0e0e0;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
color: #555;
}
td {
background-color: #e0e0e0;
color: #333;
}
input[type="text"] {
width: calc(100% - 16px);
padding: 8px;
border: none;
border-radius: 8px;
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
background-color: #e0e0e0;
}
button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: #e0e0e0;
box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
cursor: pointer;
font-size: 14px;
margin-right: 5px;
}
button:hover {
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
}
.debug-panel {
position: fixed;
top: 8%;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-height: 400px;
overflow-y: auto;
background-color: #e0e0e0;
box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
border-radius: 10px;
padding: 20px;
display: none;
z-index: 1000;
}
.close-btn {
float: right;
cursor: pointer;
font-weight: bold;
color: #333;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
z-index: 999;
}
.auto-fetch-switch-container {
display: flex;
justify-content: flex-end;
align-items: center;
margin-bottom: 10px;
}
.auto-fetch-switch-label {
margin-right: 10px;
color: #333;
font-weight: bold;
}
.auto-fetch-switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.auto-fetch-switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(24px);
}
</style>
Show full message · 431 lines Assistant2024-09-30 01:42 UTC Copy response
To reimplement the auto-fetch feature and resolve the bug you've encountered, I will help you streamline the process. Here's how you can achieve it:
Problem Identification: The auto-fetch feature relies on saving the state in cookies and retrieving it each time the page loads, which seems to be causing issues with the state persistence. Instead, using localStorage can provide a more reliable solution for saving such states.
Implementation: We'll continue to store the auto-fetch state in localStorage, which is simpler to use for this purpose in modern web applications.
Code Implementation:
Here's the modified JavaScript section along with additional changes in the HTML body where necessary:
Assistant2024-09-30 01:43 UTC Copy response
Here's the full code with the auto-fetch feature reimplemented using localStorage for state management instead of cookies:
Show full message · 413 lines Assistant2024-09-30 01:49 UTC Copy response
Below is the full code with an added link aligned to the right of the auto-fetch switch. The link points to https://cors-anywhere.herokuapp.com/corsdemo with the text "Not working? Request access here":
Show full message · 423 lines full code the fetch on load and not middle align vertical with the switch, make is so also align with the not working link as well
Assistant2024-09-30 01:52 UTC Copy response
To ensure proper alignment for all elements within the auto-fetch-switch-container, you can adjust the container layout. Here’s how you can modify your code so that the switch, label, and link align vertically and horizontally:
Show full message · 430 lines full code for results column
change the title Results
result should be truncated if it won't fit the cell, if truncation happen, make the truncated text a link and do a similar pop up like the execute detail panel
Assistant2024-09-30 01:58 UTC Copy response
To achieve the desired behavior where the result in the "Results" column is truncated and transformed into a clickable link if it exceeds the cell's width, we'll need to implement a mechanism that monitors the length of the result text. If it's too long, we'll create a link that triggers a popup, similar to the existing debug panel for execution details. Let's modify the code accordingly:
Show full message · 469 lines Assistant2024-09-30 02:03 UTC Copy response
Sorry about that! Let's make sure the overlay dimming effect is activated when the result text is truncated and a user clicks the "Read more" link. We need to ensure the overlay is displayed whenever a detail panel (like the result or debug panel) is active.
Here's the corrected and complete code:
Show full message · 479 lines adding a new record no longer execute the the record, can you kindly correct that
Assistant2024-09-30 02:10 UTC Copy response
Certainly! To ensure that a new record is executed immediately after it is created when the auto-fetch switch is enabled, let's adjust the addNewRecord function. This adjustment will directly execute the new record regardless of the auto-fetch switch state, restoring the intended behavior.
Here's the corrected code:
Show full message · 473 lines Copy first response
Not yet included in a published release.
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Result/Error</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="toggleDebugPanel(null, true)"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
document.addEventListener('DOMContentLoaded', () => {
const autoFetchCookieValue = getCookie(autoFetchKey);
const autoFetch = (autoFetchCookieValue === null) ? false : (autoFetchCookieValue === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index); // Execute scraping if auto-fetch is enabled
}
});
}
function addTableRow({ name, url, selector }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td id="result-${index}"></td>
<td id="timestamp-${index}"></td>
<td>
<button onclick="executeRecord(${index})">▶️</button>
<button onclick="removeRecord(${index})">🗑️</button>
<button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, result: '', response: '', timestamp: '' };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
if (document.getElementById('auto-fetch-switch').checked) {
executeRecord(index);
}
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
// Log changes for new records
console.log('Stored Records after adding new:', JSON.parse(localStorage.getItem(recordsKey)));
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const { url, selector } = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
document.getElementById(`timestamp-${index}`).textContent = '⏳';
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
// Note: the proxy is used for demonstration; it might not work in production
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
const resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
updateResult(index, resultText, response.data);
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
updateResult(index, `Error: ${error.message}`, error.response ? error.response.data : 'No Response Data');
});
}
function updateResult(index, result, response) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].response = response;
records[index].timestamp = new Date().toISOString(); // ISO 8601 format for UTC timestamp
localStorage.setItem(recordsKey, JSON.stringify(records));
document.getElementById(`result-${index}`).textContent = result;
document.getElementById(`timestamp-${index}`).textContent = records[index].timestamp;
// Log update for each execution
console.log(`Result updated for index ${index}:`, { result, timestamp: records[index].timestamp });
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Updated records:`, JSON.parse(localStorage.getItem(recordsKey)));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Records after deletion:`, JSON.parse(localStorage.getItem(recordsKey)));
document.location.reload();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const responseText = records[index].response || 'No Debug Data';
debugPanel.style.display = 'block';
overlay.style.display = 'block';
debugContent.innerHTML = escapeHtml(responseText);
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
function toggleAutoFetch(isEnabled) {
setCookie(autoFetchKey, isEnabled, 365);
console.log(`Auto-fetch state saved to cookie: ${isEnabled}`);
if (isEnabled) {
executeAllRecords(); // Ensure records are fetched immediately when switch is turned on
}
}
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + d.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null; // Return null if the cookie is not found
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
<!DOCTYPE html>
<html lang="en">
<!-- ... [The head remains the same] ... -->
<body>
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Result/Error</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="toggleDebugPanel(null, true)"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
// [addTableRow and other functions remain unchanged from the original code]
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
console.log(`Auto-fetch state saved to local storage: ${isEnabled}`);
if (isEnabled) {
executeAllRecords();
}
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
</body>
</html>
Key Changes and Explanation:
Replaced cookie handling with localStorage for storing the auto-fetch state. This allows a more reliable and straightforward mechanism for persisting the user's settings.
The toggleAutoFetch function now updates the auto-fetch state directly in localStorage.
Initialization during DOMContentLoaded reads auto-fetch state from localStorage instead of cookies, ensuring correct behavior post-refresh.
The rest of the scraping logic and table management functions remain unchanged as per your original implementation. Using localStorage provides a cleaner and easier-to-debug solution for settings persistence.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Scraping Tool</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #e0e0e0;
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
min-height: 100vh;
width: 100%;
box-sizing: border-box;
}
h1 {
color: #333;
text-align: center;
width: 100%;
margin: 20px 0;
}
.table-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background-color: #e0e0e0;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
border-radius: 12px;
overflow: hidden;
}
th,
td {
padding: 12px;
text-align: left;
}
th {
background-color: #e0e0e0;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
color: #555;
}
td {
background-color: #e0e0e0;
color: #333;
}
input[type="text"] {
width: calc(100% - 16px);
padding: 8px;
border: none;
border-radius: 8px;
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
background-color: #e0e0e0;
}
button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: #e0e0e0;
box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
cursor: pointer;
font-size: 14px;
margin-right: 5px;
}
button:hover {
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
}
.debug-panel {
position: fixed;
top: 8%;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-height: 400px;
overflow-y: auto;
background-color: #e0e0e0;
box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
border-radius: 10px;
padding: 20px;
display: none;
z-index: 1000;
}
.close-btn {
float: right;
cursor: pointer;
font-weight: bold;
color: #333;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
z-index: 999;
}
.auto-fetch-switch-container {
display: flex;
justify-content: flex-end;
align-items: center;
margin-bottom: 10px;
}
.auto-fetch-switch-label {
margin-right: 10px;
color: #333;
font-weight: bold;
}
.auto-fetch-switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.auto-fetch-switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(24px);
}
</style>
</head>
<body>
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Result/Error</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="toggleDebugPanel(null, true)"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
function addTableRow({ name, url, selector }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td id="result-${index}"></td>
<td id="timestamp-${index}"></td>
<td>
<button onclick="executeRecord(${index})">▶️</button>
<button onclick="removeRecord(${index})">🗑️</button>
<button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, result: '', response: '', timestamp: '' };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
if (document.getElementById('auto-fetch-switch').checked) {
executeRecord(index);
}
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
console.log('Stored Records after adding new:', JSON.parse(localStorage.getItem(recordsKey)));
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const { url, selector } = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
document.getElementById(`timestamp-${index}`).textContent = '⏳';
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
const resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
updateResult(index, resultText, response.data);
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
updateResult(index, `Error: ${error.message}`, error.response ? error.response.data : 'No Response Data');
});
}
function updateResult(index, result, response) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].response = response;
records[index].timestamp = new Date().toISOString();
localStorage.setItem(recordsKey, JSON.stringify(records));
document.getElementById(`result-${index}`).textContent = result;
document.getElementById(`timestamp-${index}`).textContent = records[index].timestamp;
console.log(`Result updated for index ${index}:`, { result, timestamp: records[index].timestamp });
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Updated records:`, JSON.parse(localStorage.getItem(recordsKey)));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Records after deletion:`, JSON.parse(localStorage.getItem(recordsKey)));
document.location.reload();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const responseText = records[index].response || 'No Debug Data';
debugPanel.style.display = 'block';
overlay.style.display = 'block';
debugContent.innerHTML = escapeHtml(responseText);
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
console.log(`Auto-fetch state saved to local storage: ${isEnabled}`);
if (isEnabled) {
executeAllRecords();
}
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
</body>
</html>
The state is now stored in localStorage instead of cookies, which simplifies the logic and enhances reliability across page reloads.
The toggleAutoFetch function both updates the localStorage and triggers executeAllRecords if auto-fetch is enabled.
All the JavaScript and HTML remains consistent with your original structure, with changes limited to the state management logic.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Scraping Tool</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #e0e0e0;
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
min-height: 100vh;
width: 100%;
box-sizing: border-box;
}
h1 {
color: #333;
text-align: center;
width: 100%;
margin: 20px 0;
}
.table-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background-color: #e0e0e0;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
border-radius: 12px;
overflow: hidden;
}
th,
td {
padding: 12px;
text-align: left;
}
th {
background-color: #e0e0e0;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
color: #555;
}
td {
background-color: #e0e0e0;
color: #333;
}
input[type="text"] {
width: calc(100% - 16px);
padding: 8px;
border: none;
border-radius: 8px;
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
background-color: #e0e0e0;
}
button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: #e0e0e0;
box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
cursor: pointer;
font-size: 14px;
margin-right: 5px;
}
button:hover {
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
}
.debug-panel {
position: fixed;
top: 8%;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-height: 400px;
overflow-y: auto;
background-color: #e0e0e0;
box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
border-radius: 10px;
padding: 20px;
display: none;
z-index: 1000;
}
.close-btn {
float: right;
cursor: pointer;
font-weight: bold;
color: #333;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
z-index: 999;
}
.auto-fetch-switch-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.auto-fetch-switch-label {
margin-right: 10px;
color: #333;
font-weight: bold;
}
.auto-fetch-switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.auto-fetch-switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(24px);
}
.request-access-link {
margin-left: 20px;
color: #2196F3;
font-weight: bold;
text-decoration: none;
}
</style>
</head>
<body>
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<div>
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<a href="https://cors-anywhere.herokuapp.com/corsdemo" class="request-access-link" target="_blank">Not working? Request access here</a>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Result/Error</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="toggleDebugPanel(null, true)"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
function addTableRow({ name, url, selector }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td id="result-${index}"></td>
<td id="timestamp-${index}"></td>
<td>
<button onclick="executeRecord(${index})">▶️</button>
<button onclick="removeRecord(${index})">🗑️</button>
<button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, result: '', response: '', timestamp: '' };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
if (document.getElementById('auto-fetch-switch').checked) {
executeRecord(index);
}
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
console.log('Stored Records after adding new:', JSON.parse(localStorage.getItem(recordsKey)));
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const { url, selector } = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
document.getElementById(`timestamp-${index}`).textContent = '⏳';
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
const resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
updateResult(index, resultText, response.data);
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
updateResult(index, `Error: ${error.message}`, error.response ? error.response.data : 'No Response Data');
});
}
function updateResult(index, result, response) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].response = response;
records[index].timestamp = new Date().toISOString();
localStorage.setItem(recordsKey, JSON.stringify(records));
document.getElementById(`result-${index}`).textContent = result;
document.getElementById(`timestamp-${index}`).textContent = records[index].timestamp;
console.log(`Result updated for index ${index}:`, { result, timestamp: records[index].timestamp });
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Updated records:`, JSON.parse(localStorage.getItem(recordsKey)));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Records after deletion:`, JSON.parse(localStorage.getItem(recordsKey)));
document.location.reload();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const responseText = records[index].response || 'No Debug Data';
debugPanel.style.display = 'block';
overlay.style.display = 'block';
debugContent.innerHTML = escapeHtml(responseText);
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
console.log(`Auto-fetch state saved to local storage: ${isEnabled}`);
if (isEnabled) {
executeAllRecords();
}
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
</body>
</html>
A <div> is used within the auto-fetch-switch-container to organize the switch and its label on one side.
An <a> link with the class request-access-link is added, styled, and positioned to the right. It opens in a new tab due to target="_blank".
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Scraping Tool</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #e0e0e0;
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
min-height: 100vh;
width: 100%;
box-sizing: border-box;
}
h1 {
color: #333;
text-align: center;
width: 100%;
margin: 20px 0;
}
.table-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background-color: #e0e0e0;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
border-radius: 12px;
overflow: hidden;
}
th,
td {
padding: 12px;
text-align: left;
}
th {
background-color: #e0e0e0;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
color: #555;
}
td {
background-color: #e0e0e0;
color: #333;
}
input[type="text"] {
width: calc(100% - 16px);
padding: 8px;
border: none;
border-radius: 8px;
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
background-color: #e0e0e0;
}
button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: #e0e0e0;
box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
cursor: pointer;
font-size: 14px;
margin-right: 5px;
}
button:hover {
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
}
.debug-panel {
position: fixed;
top: 8%;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-height: 400px;
overflow-y: auto;
background-color: #e0e0e0;
box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
border-radius: 10px;
padding: 20px;
display: none;
z-index: 1000;
}
.close-btn {
float: right;
cursor: pointer;
font-weight: bold;
color: #333;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
z-index: 999;
}
.auto-fetch-switch-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
width: 100%;
max-width: 1200px;
box-sizing: border-box;
}
.switch-label-container {
display: flex;
align-items: center;
}
.auto-fetch-switch-label {
margin-right: 10px;
color: #333;
font-weight: bold;
}
.auto-fetch-switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.auto-fetch-switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(24px);
}
.request-access-link {
color: #2196F3;
font-weight: bold;
text-decoration: none;
}
</style>
</head>
<body>
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<div class="switch-label-container">
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<a href="https://cors-anywhere.herokuapp.com/corsdemo" class="request-access-link" target="_blank">Not working? Request access here</a>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Result/Error</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="toggleDebugPanel(null, true)"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
function addTableRow({ name, url, selector }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td id="result-${index}"></td>
<td id="timestamp-${index}"></td>
<td>
<button onclick="executeRecord(${index})">▶️</button>
<button onclick="removeRecord(${index})">🗑️</button>
<button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, result: '', response: '', timestamp: '' };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
if (document.getElementById('auto-fetch-switch').checked) {
executeRecord(index);
}
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
console.log('Stored Records after adding new:', JSON.parse(localStorage.getItem(recordsKey)));
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const { url, selector } = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
document.getElementById(`timestamp-${index}`).textContent = '⏳';
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
const resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
updateResult(index, resultText, response.data);
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
updateResult(index, `Error: ${error.message}`, error.response ? error.response.data : 'No Response Data');
});
}
function updateResult(index, result, response) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].response = response;
records[index].timestamp = new Date().toISOString();
localStorage.setItem(recordsKey, JSON.stringify(records));
document.getElementById(`result-${index}`).textContent = result;
document.getElementById(`timestamp-${index}`).textContent = records[index].timestamp;
console.log(`Result updated for index ${index}:`, { result, timestamp: records[index].timestamp });
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Updated records:`, JSON.parse(localStorage.getItem(recordsKey)));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Records after deletion:`, JSON.parse(localStorage.getItem(recordsKey)));
document.location.reload();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const responseText = records[index].response || 'No Debug Data';
debugPanel.style.display = 'block';
overlay.style.display = 'block';
debugContent.innerHTML = escapeHtml(responseText);
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
console.log(`Auto-fetch state saved to local storage: ${isEnabled}`);
if (isEnabled) {
executeAllRecords();
}
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
</body>
</html>
The auto-fetch-switch-container uses flex to align its contents vertically and horizontally.
A new wrapper, switch-label-container, ensures alignment of the switch, its label, and the link within the same row.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Scraping Tool</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #e0e0e0;
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
min-height: 100vh;
width: 100%;
box-sizing: border-box;
}
h1 {
color: #333;
text-align: center;
width: 100%;
margin: 20px 0;
}
.table-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background-color: #e0e0e0;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
border-radius: 12px;
overflow: hidden;
}
th,
td {
padding: 12px;
text-align: left;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
th {
background-color: #e0e0e0;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
color: #555;
}
td {
background-color: #e0e0e0;
color: #333;
}
input[type="text"] {
width: calc(100% - 16px);
padding: 8px;
border: none;
border-radius: 8px;
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
background-color: #e0e0e0;
}
button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: #e0e0e0;
box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
cursor: pointer;
font-size: 14px;
margin-right: 5px;
}
button:hover {
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
}
.debug-panel, .result-panel {
position: fixed;
top: 8%;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-height: 400px;
overflow-y: auto;
background-color: #e0e0e0;
box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
border-radius: 10px;
padding: 20px;
display: none;
z-index: 1000;
}
.close-btn {
float: right;
cursor: pointer;
font-weight: bold;
color: #333;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
z-index: 999;
}
.auto-fetch-switch-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
width: 100%;
max-width: 1200px;
box-sizing: border-box;
}
.switch-label-container {
display: flex;
align-items: center;
}
.auto-fetch-switch-label {
margin-right: 10px;
color: #333;
font-weight: bold;
}
.auto-fetch-switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.auto-fetch-switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(24px);
}
.request-access-link {
color: #2196F3;
font-weight: bold;
text-decoration: none;
}
.result-link {
color: #2196F3;
cursor: pointer;
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<div class="switch-label-container">
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<a href="https://cors-anywhere.herokuapp.com/corsdemo" class="request-access-link" target="_blank">Not working? Request access here</a>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Results</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="toggleDebugPanel(null, true)"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<div id="result-panel" class="result-panel">
<span class="close-btn" onclick="toggleResultPanel(null, true)">×</span>
<pre id="result-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
const maxResultLength = 50; // Adjust the length for truncation as needed
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
function addTableRow({ name, url, selector }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td id="result-${index}"></td>
<td id="timestamp-${index}"></td>
<td>
<button onclick="executeRecord(${index})">▶️</button>
<button onclick="removeRecord(${index})">🗑️</button>
<button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, result: '', response: '', timestamp: '' };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
if (document.getElementById('auto-fetch-switch').checked) {
executeRecord(index);
}
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
console.log('Stored Records after adding new:', JSON.parse(localStorage.getItem(recordsKey)));
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const { url, selector } = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
document.getElementById(`timestamp-${index}`).textContent = '⏳';
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
const resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
updateResult(index, resultText, response.data);
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
updateResult(index, `Error: ${error.message}`, error.response ? error.response.data : 'No Response Data');
});
}
function updateResult(index, result, response) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].response = response;
records[index].timestamp = new Date().toISOString();
localStorage.setItem(recordsKey, JSON.stringify(records));
let displayResult = result;
if (result.length > maxResultLength) {
displayResult = `${result.substring(0, maxResultLength)}... <span class="result-link" onclick="toggleResultPanel(${index}, false)">Read more</span>`;
}
document.getElementById(`result-${index}`).innerHTML = displayResult;
document.getElementById(`timestamp-${index}`).textContent = records[index].timestamp;
console.log(`Result updated for index ${index}:`, { result, timestamp: records[index].timestamp });
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Updated records:`, JSON.parse(localStorage.getItem(recordsKey)));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Records after deletion:`, JSON.parse(localStorage.getItem(recordsKey)));
document.location.reload();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const responseText = records[index].response || 'No Debug Data';
debugPanel.style.display = 'block';
overlay.style.display = 'block';
debugContent.innerHTML = escapeHtml(responseText);
}
function toggleResultPanel(index, close = false) {
const resultPanel = document.getElementById('result-panel');
const resultContent = document.getElementById('result-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
resultPanel.style.display = 'none';
overlay.style.display = 'none';
resultContent.innerHTML = '';
return;
}
const resultText = records[index].result || 'No Result Data';
resultPanel.style.display = 'block';
overlay.style.display = 'block';
resultContent.innerHTML = escapeHtml(resultText);
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
console.log(`Auto-fetch state saved to local storage: ${isEnabled}`);
if (isEnabled) {
executeAllRecords();
}
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
</body>
</html>
Explanation:
Truncating Results: The maxResultLength variable defines the threshold for truncating the result text. If the result exceeds this length, it is truncated, and a "Read more" link is appended.
Result Panel: Similar to the debug panel, a new result-panel is implemented, which displays the full result when the truncated text is clicked.
CSS Adjustments: The text-overflow: ellipsis; style ensures that any text overflow is visually indicated, although the clickable link ultimately handles user access to the full text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Scraping Tool</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #e0e0e0;
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
min-height: 100vh;
width: 100%;
box-sizing: border-box;
}
h1 {
color: #333;
text-align: center;
width: 100%;
margin: 20px 0;
}
.table-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background-color: #e0e0e0;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
border-radius: 12px;
overflow: hidden;
}
th,
td {
padding: 12px;
text-align: left;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
th {
background-color: #e0e0e0;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
color: #555;
}
td {
background-color: #e0e0e0;
color: #333;
}
input[type="text"] {
width: calc(100% - 16px);
padding: 8px;
border: none;
border-radius: 8px;
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
background-color: #e0e0e0;
}
button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: #e0e0e0;
box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
cursor: pointer;
font-size: 14px;
margin-right: 5px;
}
button:hover {
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
}
.debug-panel, .result-panel {
position: fixed;
top: 8%;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-height: 400px;
overflow-y: auto;
background-color: #e0e0e0;
box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
border-radius: 10px;
padding: 20px;
display: none;
z-index: 1000;
}
.close-btn {
float: right;
cursor: pointer;
font-weight: bold;
color: #333;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
z-index: 999;
}
.auto-fetch-switch-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
width: 100%;
max-width: 1200px;
box-sizing: border-box;
}
.switch-label-container {
display: flex;
align-items: center;
}
.auto-fetch-switch-label {
margin-right: 10px;
color: #333;
font-weight: bold;
}
.auto-fetch-switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.auto-fetch-switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(24px);
}
.request-access-link {
color: #2196F3;
font-weight: bold;
text-decoration: none;
}
.result-link {
color: #2196F3;
cursor: pointer;
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<div class="switch-label-container">
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<a href="https://cors-anywhere.herokuapp.com/corsdemo" class="request-access-link" target="_blank">Not working? Request access here</a>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Results</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="closePanels()"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<div id="result-panel" class="result-panel">
<span class="close-btn" onclick="toggleResultPanel(null, true)">×</span>
<pre id="result-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
const maxResultLength = 50; // Adjust the length for truncation as needed
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
function addTableRow({ name, url, selector }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td id="result-${index}"></td>
<td id="timestamp-${index}"></td>
<td>
<button onclick="executeRecord(${index})">▶️</button>
<button onclick="removeRecord(${index})">🗑️</button>
<button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, result: '', response: '', timestamp: '' };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
if (document.getElementById('auto-fetch-switch').checked) {
executeRecord(index);
}
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
console.log('Stored Records after adding new:', JSON.parse(localStorage.getItem(recordsKey)));
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const { url, selector } = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
document.getElementById(`timestamp-${index}`).textContent = '⏳';
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
const resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
updateResult(index, resultText, response.data);
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
updateResult(index, `Error: ${error.message}`, error.response ? error.response.data : 'No Response Data');
});
}
function updateResult(index, result, response) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].response = response;
records[index].timestamp = new Date().toISOString();
localStorage.setItem(recordsKey, JSON.stringify(records));
let displayResult = result;
if (result.length > maxResultLength) {
displayResult = `${result.substring(0, maxResultLength)}... <span class="result-link" onclick="toggleResultPanel(${index}, false)">Read more</span>`;
}
document.getElementById(`result-${index}`).innerHTML = displayResult;
document.getElementById(`timestamp-${index}`).textContent = records[index].timestamp;
console.log(`Result updated for index ${index}:`, { result, timestamp: records[index].timestamp });
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Updated records:`, JSON.parse(localStorage.getItem(recordsKey)));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Records after deletion:`, JSON.parse(localStorage.getItem(recordsKey)));
document.location.reload();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const responseText = records[index].response || 'No Debug Data';
debugPanel.style.display = 'block';
overlay.style.display = 'block';
debugContent.innerHTML = escapeHtml(responseText);
}
function toggleResultPanel(index, close = false) {
const resultPanel = document.getElementById('result-panel');
const resultContent = document.getElementById('result-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
resultPanel.style.display = 'none';
overlay.style.display = 'none';
resultContent.innerHTML = '';
return;
}
const resultText = records[index].result || 'No Result Data';
resultPanel.style.display = 'block';
overlay.style.display = 'block';
resultContent.innerHTML = escapeHtml(resultText);
}
function closePanels() {
toggleDebugPanel(null, true);
toggleResultPanel(null, true);
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
console.log(`Auto-fetch state saved to local storage: ${isEnabled}`);
if (isEnabled) {
executeAllRecords();
}
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
</body>
</html>
Key Additions:
Overlay Management: The closePanels function handles closing both the debug and result panels, hiding the overlay.
Overlay Click Handling: Clicking the overlay now invokes closePanels, ensuring any open panel is closed and the dimming is removed.
Result Truncation: The result text is truncated based on maxResultLength, with a "Read more" link that opens the full text in a modal-like panel if the content is longer than what fits.
These changes should provide the dimming effect when the result panel is open and restore the interface to normal when closed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Scraping Tool</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #e0e0e0;
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
min-height: 100vh;
width: 100%;
box-sizing: border-box;
}
h1 {
color: #333;
text-align: center;
width: 100%;
margin: 20px 0;
}
.table-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background-color: #e0e0e0;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
border-radius: 12px;
overflow: hidden;
}
th,
td {
padding: 12px;
text-align: left;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
th {
background-color: #e0e0e0;
box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
color: #555;
}
td {
background-color: #e0e0e0;
color: #333;
}
input[type="text"] {
width: calc(100% - 16px);
padding: 8px;
border: none;
border-radius: 8px;
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
background-color: #e0e0e0;
}
button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: #e0e0e0;
box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
cursor: pointer;
font-size: 14px;
margin-right: 5px;
}
button:hover {
box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
}
.debug-panel, .result-panel {
position: fixed;
top: 8%;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-height: 400px;
overflow-y: auto;
background-color: #e0e0e0;
box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
border-radius: 10px;
padding: 20px;
display: none;
z-index: 1000;
}
.close-btn {
float: right;
cursor: pointer;
font-weight: bold;
color: #333;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
display: none;
z-index: 999;
}
.auto-fetch-switch-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
width: 100%;
max-width: 1200px;
box-sizing: border-box;
}
.switch-label-container {
display: flex;
align-items: center;
}
.auto-fetch-switch-label {
margin-right: 10px;
color: #333;
font-weight: bold;
}
.auto-fetch-switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.auto-fetch-switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 2px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(24px);
}
.request-access-link {
color: #2196F3;
font-weight: bold;
text-decoration: none;
}
.result-link {
color: #2196F3;
cursor: pointer;
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Web Scraping Tool</h1>
<div class="table-container">
<div class="auto-fetch-switch-container">
<div class="switch-label-container">
<span class="auto-fetch-switch-label">Auto Fetch on Load</span>
<label class="auto-fetch-switch">
<input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
<span class="slider"></span>
</label>
</div>
<a href="https://cors-anywhere.herokuapp.com/corsdemo" class="request-access-link" target="_blank">Not working? Request access here</a>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Results</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!-- Dynamic rows will be added here -->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">✚</button></td>
</tr>
</tbody>
</table>
</div>
<div id="overlay" class="overlay" onclick="closePanels()"></div>
<div id="debug-panel" class="debug-panel">
<span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
<pre id="debug-content"></pre>
</div>
<div id="result-panel" class="result-panel">
<span class="close-btn" onclick="toggleResultPanel(null, true)">×</span>
<pre id="result-content"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
const maxResultLength = 50; // Adjust the length for truncation as needed
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
console.log('Auto-Fetch State on Load:', autoFetch);
console.log('Stored Records:', JSON.parse(localStorage.getItem(recordsKey)));
loadRecords(autoFetch);
});
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
function addTableRow({ name, url, selector }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td id="result-${index}"></td>
<td id="timestamp-${index}"></td>
<td>
<button onclick="executeRecord(${index})">▶️</button>
<button onclick="removeRecord(${index})">🗑️</button>
<button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, result: '', response: '', timestamp: '' };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
executeRecord(index); // Execute the record immediately when added
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
console.log('Stored Records after adding new:', JSON.parse(localStorage.getItem(recordsKey)));
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const { url, selector } = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
document.getElementById(`timestamp-${index}`).textContent = '⏳';
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
const resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
updateResult(index, resultText, response.data);
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
updateResult(index, `Error: ${error.message}`, error.response ? error.response.data : 'No Response Data');
});
}
function updateResult(index, result, response) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].response = response;
records[index].timestamp = new Date().toISOString();
localStorage.setItem(recordsKey, JSON.stringify(records));
let displayResult = result;
if (result.length > maxResultLength) {
displayResult = `${result.substring(0, maxResultLength)}... <span class="result-link" onclick="toggleResultPanel(${index}, false)">Read more</span>`;
}
document.getElementById(`result-${index}`).innerHTML = displayResult;
document.getElementById(`timestamp-${index}`).textContent = records[index].timestamp;
console.log(`Result updated for index ${index}:`, { result, timestamp: records[index].timestamp });
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Updated records:`, JSON.parse(localStorage.getItem(recordsKey)));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
console.log(`Records after deletion:`, JSON.parse(localStorage.getItem(recordsKey)));
document.location.reload();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const responseText = records[index].response || 'No Debug Data';
debugPanel.style.display = 'block';
overlay.style.display = 'block';
debugContent.innerHTML = escapeHtml(responseText);
}
function toggleResultPanel(index, close = false) {
const resultPanel = document.getElementById('result-panel');
const resultContent = document.getElementById('result-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
resultPanel.style.display = 'none';
overlay.style.display = 'none';
resultContent.innerHTML = '';
return;
}
const resultText = records[index].result || 'No Result Data';
resultPanel.style.display = 'block';
overlay.style.display = 'block';
resultContent.innerHTML = escapeHtml(resultText);
}
function closePanels() {
toggleDebugPanel(null, true);
toggleResultPanel(null, true);
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
console.log(`Auto-fetch state saved to local storage: ${isEnabled}`);
if (isEnabled) {
executeAllRecords();
}
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
</script>
</body>
</html>
Key Change:
Executing New Records: The addNewRecord function immediately calls executeRecord(index) after a new record is added to ensure it runs right away, providing results as expected. This change ensures that the function operates independently of the auto-fetch switch state specifically for new entries.