能否在打开新标签页时缓存文档最后修改日期至localStorage并后续调用?
Yes, this is achievable—but with a critical caveat tied to browser security rules. Let's break down your example code, fix its issues, and cover the constraints you'll run into.
First: Fixing Your Code's Core Issue
Your current code tries to save this.document.lastModified, which refers to the original page's last modified date, not the new tab's target document. To get the target site's date, you need to access the new window's document object. Here's the corrected version:
// Retrieve existing cached date first (if any) let modified = localStorage.getItem('site'); // Open the target tab const checker = window.open('https://www.example.com', '_blank'); setTimeout(() => { try { // Access the new tab's document (only works if same-origin!) const targetLastModified = checker.document.lastModified; localStorage.setItem('site', targetLastModified); console.log('Successfully cached date:', targetLastModified); } catch (error) { console.error('Failed to access target document:', error.message); } // Close the tab once operation is complete checker.close(); }, 1000); return false;
The Big Constraint: Same-Origin Policy
This approach will only work if the target URL shares the same origin as your original page. The same origin means matching protocol (http/https), domain, and port.
If the target is cross-origin (e.g., your page is on https://yoursite.com and you're opening https://example.com), the browser will throw a SecurityError—it blocks scripts from accessing properties of a window from a different origin to prevent malicious behavior like data theft.
What If You Need Cross-Origin Support?
If the target site isn't same-origin, you can't directly access its document.lastModified via a new tab. Instead, consider these workarounds:
- Use a server-side proxy: Have your backend fetch the target site's
Last-ModifiedHTTP header, then pass that value to your frontend to cache in localStorage. This avoids browser security restrictions because the request comes from your server. - Check for a public API: Some sites expose metadata (like last modified dates) via an API endpoint you can call directly from your frontend (if CORS is enabled for the endpoint).
How to Use the Cached Value Later
Once you've successfully stored the date in localStorage, you can retrieve and use it anytime with:
const cachedModifiedDate = localStorage.getItem('site'); if (cachedModifiedDate) { // Integrate the date into your logic console.log('Last cached modified date:', cachedModifiedDate); }
Note that localStorage persists across browser sessions (until manually cleared), so the value will stay available even if the user closes and reopens the browser.
内容的提问来源于stack exchange,提问作者Tima Donbragoni

