You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从文本文件随机设置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:

Randomly Load URL from Text File into Iframe

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.txt is 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(' ') with split('\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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:40:25