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

在PyScript中嵌入YouTube视频的iframe无法连接问题求助

解决pyscript.com托管页面中YouTube iframe无法连接的问题

这个问题的核心是pyscript.com的默认内容安全策略(CSP)限制了YouTube iframe的加载,浏览器会因为CSP规则拦截跨域的iframe请求,导致显示"www.youtube.com refused to connect"。

解决步骤:

在HTML的<head>部分添加自定义的CSP meta标签,明确允许加载YouTube的iframe资源,同时保留pyscript运行所需的资源权限。

修改后的完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <!-- 添加自定义CSP规则 -->
    <meta http-equiv="Content-Security-Policy" content="
        default-src 'self';
        script-src 'self' https://pyscript.net/releases/2023.05.1/pyscript.js;
        style-src 'self' https://pyscript.net/releases/2023.05.1/pyscript.css;
        frame-src 'self' https://www.youtube.com https://youtube.com;
        img-src 'self' data:;
        media-src 'self';
        connect-src 'self' https://pyscript.net;
    ">
    <link rel="stylesheet" href="https://pyscript.net/releases/2023.05.1/pyscript.css" />
    <script defer src="https://pyscript.net/releases/2023.05.1/pyscript.js"></script>
    <style>
    </style>
</head>
<body>
    <div>  
        <iframe width="560" height="315" src="https://www.youtube.com/embed/4xvC7Rlf2yw?si=mYYBe5-LoqkH-iHL" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
    </div>
</body>
</html>

关键说明:

  • frame-src 'self' https://www.youtube.com https://youtube.com; 这一行是解决iframe加载问题的核心,明确允许页面嵌入来自YouTube的iframe资源。
  • 其他规则确保pyscript的CSS、JS文件以及必要的网络请求能正常加载,避免破坏原有功能。

内容的提问来源于stack exchange,提问作者Ausk Fullex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:08:22