Iframe“(站点名称)拒绝连接。” 错误

ifa*_*txh 6 html iframe google-chrome

我在项目中使用的 iframe 元素的内容是“(站点名称)拒绝连接”。我收到错误,如何修复此错误?

<iframe src="https://www.google.com/" frameborder="0"></iframe>
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/fatihege/2he1nuyf/

小智 10

几个月来我一直在尝试解决这个问题,最后找到了一个非常简单的解决方案,但我没有看到任何人提到过。如果您尝试使用 iframe 包含不允许您访问的网站,请创建您自己的 php 文件,我将其命名为 iframe.php。在该文件中,放入以下内容:

<!DOCTYPE html><html><?php echo file_get_contents($_REQUEST['url']); ?></html>
Run Code Online (Sandbox Code Playgroud)

然后,在您的 iframe 中,使用 src url 'iframe.php?url=http://www.website.com'。


sco*_*chy 3

这不是您的代码,因为网站可以阻止自己被框架。

这是因为根据 mozilla 文档设置了某个标头(X-Frame-Options): https: //developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
  <iframe src="https://www.google.com/" frameborder="0"></iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但对于另一个域(example.com):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
  <iframe src="https://www.example.com/" frameborder="0"></iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果您不允许查看该站点,您可以依靠服务器端来执行此操作。基本上,概念是服务器将获取文件并将其附加到给定位置。

正如@Dale 的回答所指出的,这可以使用 php 来完成。对于那些使用其他服务器端语言的人来说,基本上应用相同的原理。在节点中的实现将类似于:

const express = require('express');
const fs = require('fs');
const { execSync } = require('child_process');
const app = new express();
const PORT = 3000;

const fetchWebsite = (url) => {
  execSync(`wget -q -O - ${url} > site.html`,
    (error, stdout, stderr) => {
      if (error !== null) {
        return false;
      }
  });
}

app.get('/', async (req, res) => {
  fs.writeFileSync('site.html', '', () => console.log('Created site.html'));
  fs.createReadStream('site.html').pipe(res);
  fetchWebsite('https://www.stackoverflow.com');
});

app.listen(PORT, () => {console.log("Listening at port: ", PORT)} )
Run Code Online (Sandbox Code Playgroud)

当然,这假设您使用的是标准 Linux 服务器并且已经安装了express 模块。