从书签内部关闭书签

Close a bookmarklet from inside it

本文关键字:书签 内部      更新时间:2023-09-26

我正在创建一个书签,它执行类似于亚马逊将任何内容添加到您的愿望清单书签(http://www.amazon.com/wishlist/get-button)的功能。我正在尝试制作一个取消按钮,但我似乎无法让它工作。

如何制作一个取消按钮,该按钮将显示在书签的 iframe ,并关闭 iframe?

我尝试使用:从 iframe 内部window.close来做到这一点,但这不起作用。我也尝试使用parent.document.body.removeChild(parent.document.getElementById('iframe')),但我遇到了跨域权限问题。有什么想法吗?

iframe 包装在div 中。 将取消按钮放在div 内部,但在 iframe 外部,以便取消按钮实际上位于父页面中。这避免了跨源问题。

有一些方法可以解决跨源问题,但这是迄今为止针对特定问题的最简单的解决方案。

你将不得不使用 window.postMessage 来告诉父窗口中的函数关闭它。

如果可以修改父页面

您可以修改父页面(包含框架的页面)吗?如果可以,你可以做到:

function remove()
{
  document.body.removeChild(document.getElementById('myIframe'));
  document.write("Frame removed")
}
<iframe id="myIframe" src="https://stacksnippets.net/js"></iframe>
<br/>
<span onclick="remove()" >Click me to remove the frame from the page</span>

代替span元素,您可以使用任何您喜欢的元素,例如按钮。

您还可以准备这两个页面,并使它们与postMessage进行通信,彼此之间的逻辑类似于:

在 iframe 页面中输入一个 JavaScript,如下所示:

parent.postMessage('close me', '*')

也许您希望将上面的代码包装到一个函数中,以通过按钮单击事件运行。

在父页面中放置一个类似于以下内容的 javascript:

    window.addEventListener('message', (event) =>
    {
        if(event.data == 'close me')
        {
             yourCloseIframeFunction();
        }
     }, false);

也许您需要进行调整才能在您的页面中执行它。

如果您因为父页面不是您的而无法修改父页面

由于跨源策略,您无法通过从嵌套 iframe 运行 javascript 来从中删除元素。但是,从显示到 iframe 的页面中,您可以通过以下方式阻止显示您的内容 让浏览器导航到其他地方,例如空白或不存在的页面,例如:

if (window.top != window.self)
{
  window.location.href = 'nopage.html';
}
my content of the iframed page will not show<br/>
my content of the iframed page will not show<br/>
my content of the iframed page will not show<br/>
my content of the iframed page will not show<br/>
my content of the iframed page will not show<br/>
my content of the iframed page will not show<br/>

如果您愿意,也可以像这样自动清空它:

if (window.self != window.top)
{
  document.body.innerText = 'This page cannot be seen from your nested iframes! Sorry';
}
The content of you page<br/>
The content of you page<br/>
The content of you page<br/>
...<br/>
<button onclick="hide()">Don't show page content</button>

或者只需在单击按钮时清空 iframed 页面内容本身。

只需将以下代码放入 iframed 页面即可尝试这样的解决方案:

function removeContent()
{
  document.body.innerText = '';
}
The content of you page<br/>
The content of you page<br/>
The content of you page<br/>
...<br/>
<button onclick="removeContent()">Don't show page content</button>