【问题标题】:How to close Bookmarklet using iframe?如何使用 iframe 关闭书签?
【发布时间】:2017-01-31 12:34:38
【问题描述】:

我为我的网站设计了书签。因此,使用 iframe 创建的小书签。 iframe 和 iframe 源在脚本中声明。

我已经为我的源页面设置了关闭按钮并声明了回调函数,但它不起作用。

点击关闭按钮

显示以下错误。

(DOMException: Blocked a frame with origin "http://localhost:8050" from access cross-origin frame. at HTMLButtonElement.onclick (http://localhost:8050/researcher_voice/iframe.html:19:172))。

书签:

 <a class="article-bookmark" href="javascript: (function(){

        var iframeSrc = 'http://localhost:8050/researcher_20voice/iframe.html';
        var iframeStyle = 'position: fixed; z-index: 999999; width: 500px; height: 300px; left:300px; right: 0; top: 200px; border: none; overflow: hidden;                   background-color: black';
        var iframe = document.createElement('iframe');
        iframe.setAttribute('src', iframeSrc);
        iframe.setAttribute('id', 'kew-modal');
        iframe.setAttribute('style', iframeStyle);


        var body = document.getElementsByTagName('body')[0];
        body.appendChild(iframe);


    }).call(this);">Bookmarklet</a> 

关闭按钮:

 function closeIframe() {
         var iframe = document.getElementById('id');
         iframe.parentNode.removeChild(iframe);
    }

【问题讨论】:

  • 如果内容来自同一个来源,你可以 - 但你需要使用 document.getElementById('kew-modal') 而不是 ("id") - 因为它可能不是来自同一个来源,你将被禁止
  • 而且我也使用过 document.getElementById('kew-modal') 但它重复了相同的跨域错误。
  • 所以答案是否定的

标签: javascript


【解决方案1】:

我在创建书签时也遇到了这个问题,就像 Pinterest 的 Pin It 一样。

解决跨域问题的唯一方法是在 iframe 内的页面与 GitHub 上的此示例之后的父页面之间发布事件:

https://gist.github.com/kn0ll/1020251

我已经在另一个线程上发布了答案: https://stackoverflow.com/a/43030280/3958617

还在另一个线程上找到了另一个示例: https://stackoverflow.com/a/21882581/3958617

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多