强制 iFrame 链接(在嵌入的 Google 文档中)在新窗口打开

15

非常奇怪的是,似乎没有办法将Google文档链接设置为在新窗口中打开(target="_blank")。

当发布Google文档并使用嵌入功能时,会生成一个iframe片段:

<iframe src="https://docs.google.com/document/pub?id=1mfSz_3cWh6eW-X3EhQTtCoZ33Km131An8Kyvmuxi5oM&amp;embedded=true"></iframe>

文档中的所有链接都将在 iFrame 中打开,并通过 Google 的重定向服务进行重定向: http://www.google.com/url?q=

有没有办法让这些链接在新窗口中打开?我知道可能存在跨域脚本问题,所以奇怪的是 Google 没有简单的方法来实现这个...

有没有办法让这些链接在新窗口中打开?我知道可能存在跨域脚本问题,所以奇怪的是 Google 没有简单的方法来实现这个...

4个回答

6
这是我的解决方案,避免使用iframe srcdoc,因为它在IE中不受支持。样式是可选的。
<style>
    body { margin: 0; padding: 0; }
    iframe { margin-left: 2vw; margin-top: 2vh; height: 90vh; width: 90vw; }
</style>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<iframe srcdoc="" frameborder="0" scrolling="no"></iframe>

<script>
    $(function() {
        $.get("https://docs.google.com/document/pub?id=1mfSz_3cWh6eW-X3EhQTtCoZ33Km131An8Kyvmuxi5oM&amp;embedded=true", function(html) {
            var contents = $("iframe").contents();

            contents.find("html").html(html);

            setTimeout(function() {
                contents.find('a[href^="http://"]').attr("target", "_blank");
                contents.find('a[href^="https://"]').attr("target", "_blank");
            }, 1000); // Actually not sure if timeout is required here...
        });
    });
</script>

谢谢分享!这样做有什么相关的缺点吗? - Rudolf Real
1
@FabricioPH 相关的缺点 - SEO - 不确定谷歌是否正确地索引了这样的页面。我的一个例子 - http://genesis.re/cruitment/ - 您可以查看源代码。 - Mars Robertson
Gist链接是404,考虑将其删除。 - blackboxlogic
第一个想法:如果这让你不舒服,你可以自己编辑答案。 - Mars Robertson

5

好的,由于没有更好的选择,我决定用Curl获取Google文档的URL并在加载到iFrame之前进行一些jQuery魔法。

Curl.php

curl_setopt($ch, CURLOPT_URL, $Url);
[...]
$("#header").hide()
$("#footer").hide()
$('a[href^="http://"]').attr("target", "_blank");

Page.html

$("#google_content").html("<iframe width='100%' height='600' frameborder='0' src='http://www.example.com/Curl/Curl.php'></iframe>");

谷歌,这真的是推荐的解决方案吗? ;)

我知道已经很久了,但这是你让它工作的唯一方式吗? - Matt
不幸的是,是的 - 但今天有更好的解决方案希望!? - dani
这是我找到的一个客户端JS解决方案:https://gist.github.com/psjinx/1f2317a50eb2b506ed84 - avioing

0
一个更简单的、非编码的解决方法是嵌入来自Google Drive的谷歌文档,而不是“发布”的谷歌文档。权限可以让您确保文档的查看和传播受到限制。
请点击this link并查看“Google Drive”下的部分。
这对我们来说完美地解决了问题——链接在打开时没有警告,这可能会吓到用户。

0

在我们的资源页面(https://ingeniumschools.org/icms/resources)上使用Google Doc发布功能时,我们遇到了同样的问题。最终用户会看到drive.google.com拒绝连接的图像,因为链接试图在iframe中打开。 Google Refuses to Connect in iframe embed

上面关于CURL的解决方案对我们不起作用,因为我们需要让文档编辑器变得简单。

我发现这个问题提供了一点提示,我想尝试一下。

  1. 按照通常的方式发布Google Doc。
  2. 在提供的iframe嵌入代码中,将src属性与此格式的URL交换:https://docs.google.com/document/d/e/ENTER_YOUR_DOCS_ID/pub?preview

这将嵌入一些烦人的 Google 头部和页脚,但链接将在新窗口中打开而不是 iframe。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接