如何从文本文件随机设置iframe的src,实现每次打开加载不同URL
Alright, let's figure out how to make your iframe load a random URL from that text file every time it's opened. Here's a straightforward approach using vanilla JavaScript—no fancy libraries needed:
1. Prep Your Text File
First, let's confirm the format. Your example uses entries like Site1^ https://www.google.com/ Site2^ https://www.facebook.com/—either a single line with space-separated entries or each entry on its own line works. For better readability, I'd recommend each entry on a new line:
Site1^ https://www.google.com/
Site2^ https://www.facebook.com/
Site3^ https://www.example.com/
Save this as urls.txt and host it alongside your HTML page (same domain is key to avoid cross-origin issues).
2. Basic HTML Structure
Add an iframe to your page with an ID so we can target it easily:
<iframe id="randomFrame" width="800" height="600" frameborder="0"></iframe>
3. JavaScript to Fetch, Parse, and Randomize
Add this script to your page (either in a <script> tag or external JS file) to handle the heavy lifting:
// Wait for the page to fully load before running code document.addEventListener('DOMContentLoaded', async () => { const iframe = document.getElementById('randomFrame'); try { // Fetch the text file containing our URLs const response = await fetch('urls.txt'); if (!response.ok) throw new Error('Could not load URL list'); // Get the raw text content from the file const textData = await response.text(); // Parse the text to extract valid URLs // Split entries (adjust split method if using newlines instead of spaces) const entries = textData.split(' ').filter(item => item.trim() !== ''); const urlList = entries.map(entry => { // Split each entry by "^ " to separate site name and URL const parts = entry.split('^ '); return parts[1]?.trim(); // Grab the URL part and clean up whitespace }).filter(url => url); // Remove any empty/invalid entries if (urlList.length === 0) throw new Error('No valid URLs found in the file'); // Pick a random URL from the list const randomIndex = Math.floor(Math.random() * urlList.length); const selectedUrl = urlList[randomIndex]; // Assign the random URL to the iframe iframe.src = selectedUrl; } catch (error) { console.error('Error loading random URL:', error); // Fallback to a safe URL if something goes wrong iframe.src = 'https://www.example.com/'; } });
4. Key Notes to Keep in Mind
- Cross-Origin Restrictions: If your
urls.txtis hosted on a different domain, you'll need the server to enable CORS (Cross-Origin Resource Sharing) to let your page access it. For same-domain hosting, this isn't an issue. - Text File Format Adjustment: If you use newlines instead of spaces to separate entries, replace
split(' ')withsplit('\n')in the code—it's more reliable for line-separated content. - Security: Only include trusted URLs in your text file. Loading unvetted sites in an iframe can pose security risks like clickjacking.
内容的提问来源于stack exchange,提问作者Ritesh Ranjan

