基于EventSource实现关键字检测后自动刷新页面的技术求助
Solution: Monitor Log Lines to Trigger Page Refresh
Got it, let's adjust your existing EventSource script to monitor the log lines and trigger a page refresh when the right conditions are met. Here's the modified code with explanations:
<script type="text/javascript"> if(typeof(EventSource)!== "undefined") { // Track if we're waiting for a "completed" event after seeing "starting" let waitingForCompleted = false; const eSource = new EventSource("dyntasks.php"); eSource.onmessage = function(event) { // Split the incoming data into individual lines, filter out empty lines const logLines = event.data.split('\n').filter(line => line.trim() !== ''); // Make sure we have at least two lines (since last line is always "updating...") if (logLines.length >= 2) { // Grab the second-to-last line (skip the final "updating..." line) const targetLine = logLines[logLines.length - 2]; // Switch to monitoring mode if we see "starting" and aren't already waiting if (targetLine.includes("starting") && !waitingForCompleted) { waitingForCompleted = true; console.log("Now watching for task completion..."); } // If we're in monitoring mode and see "completed", refresh the page if (waitingForCompleted && targetLine.includes("completed")) { console.log("Task finished! Refreshing page..."); waitingForCompleted = false; // Reset state for future tasks window.location.reload(); } } // Keep updating the UI with the full log as before document.getElementById("serverData").innerHTML = event.data; }; } </script>
Key Changes Breakdown:
- Line Handling: We split the incoming log data into lines and filter out empty entries to avoid issues with trailing newlines or blank lines in the log.
- State Tracking: The
waitingForCompletedvariable acts as a flag to remember when we need to watch for a "completed" line after spotting "starting". - Target Line Selection: We explicitly target the second-to-last line (since the final line is always "updating...") to check for our keywords.
- Safety Check: We add a guard clause to ensure there are at least two lines before accessing the second-to-last one, preventing errors if the log is initially short.
- Refresh Logic: When we detect "completed" while in monitoring mode, we reset the flag and trigger a full page refresh with
window.location.reload().
This script maintains your original functionality of updating the log display, while adding the monitoring and refresh behavior you need.
内容的提问来源于stack exchange,提问作者Giovanni Recchia
相关产品推荐
相关产品推荐

