新手开发者求助:如何用JavaScript实现查看其他网站源码功能
Hey there! I see you're trying to expand your "view source" tool to work with external sites like example.com—great goal! The catch with your current code is that it only grabs the current page's HTML because of a browser security rule called the Same-Origin Policy. This rule stops JavaScript from directly fetching content from other domains to keep users safe from malicious scripts.
Let's break down how to fix this:
Why Your Current Code Only Works for the Current Page
First, let's clean up your existing code (I fixed a tiny typo: innerHTMLz → innerHTML):
function viewSource() { var source = "<html>"; source += document.getElementsByTagName('html')[0].innerHTML; source += "</html>"; source = source.replace(/</g, "<").replace(/>/g, ">"); source = "<pre>" + source + "</pre>"; const sourceWindow = window.open('', 'Source of page', 'height=800,width=800,scrollbars=1,resizable=1'); sourceWindow.document.write(source); sourceWindow.document.close(); if (window.focus) sourceWindow.focus(); }
<button type="button" onclick="viewSource()">View Source</button>
This code uses document.getElementsByTagName('html')[0].innerHTML, which only accesses the DOM of the page it's running on—so it can't reach external sites.
The Fix: Use a Backend Proxy
Since browsers block cross-domain requests, you'll need a simple backend server to fetch the external site's source code for you. Servers don't have the same-origin restriction, so they can pull content from any site.
Here's a straightforward example using Node.js with Express (you can use any backend language you're comfortable with):
Step 1: Set Up a Simple Proxy Server
Create a file named server.js:
const express = require('express'); const axios = require('axios'); const app = express(); const port = 3000; // Allow your frontend to communicate with this server app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next(); }); // Endpoint to fetch external site source code app.get('/get-source', async (req, res) => { const url = req.query.url; if (!url) { return res.status(400).send('Please provide a URL'); } try { const response = await axios.get(url); res.send(response.data); } catch (error) { res.status(500).send(`Error fetching source: ${error.message}`); } }); app.listen(port, () => { console.log(`Proxy server running on http://localhost:${port}`); });
Install the required dependencies:
npm install express axios
Start the server:
node server.js
Step 2: Update Your Frontend Code
Modify your frontend to call the backend proxy instead of accessing the current DOM. We'll add an input so users can enter any URL they want to inspect:
<input type="text" id="urlInput" placeholder="Enter URL (e.g., https://example.com)"> <button type="button" onclick="viewExternalSource()">View External Source</button> <script> async function viewExternalSource() { const url = document.getElementById('urlInput').value; if (!url) { alert('Please enter a URL first!'); return; } try { // Fetch source code via our backend proxy const response = await fetch(`http://localhost:3000/get-source?url=${encodeURIComponent(url)}`); const source = await response.text(); // Format the source for readable display const formattedSource = `<pre>${source.replace(/</g, "<").replace(/>/g, ">")}</pre>`; // Open the formatted source in a new window const sourceWindow = window.open('', 'Source of page', 'height=800,width=800,scrollbars=1,resizable=1'); sourceWindow.document.write(formattedSource); sourceWindow.document.close(); if (window.focus) sourceWindow.focus(); } catch (error) { alert(`Oops, failed to fetch source: ${error.message}`); } } </script>
Key Things to Keep in Mind
- Security: In production, don't use
Access-Control-Allow-Origin: *—instead, specify your frontend's exact domain to prevent misuse. You can also add checks to block access to internal or malicious URLs. - Encoding: Some sites use non-standard character encodings; Axios usually handles this automatically, but you might need to adjust if you run into garbled text.
- Rate Limits: Be mindful of how often you fetch from external sites—some might block repeated requests from your proxy.
内容的提问来源于stack exchange,提问作者Shimanto Neer

