从书签内部关闭书签
Close a bookmarklet from inside it
我正在创建一个书签,它执行类似于亚马逊将任何内容添加到您的愿望清单书签(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>
- 内部分区字体大小获胜'调整浏览器窗口大小时不会随媒体查询而更改
- 调用函数内部的函数
- 如何使用js将SNAPSHOT内部版本号转换为3位数的整数
- 在phonegap应用程序内部重定向不起作用
- 使用此选项选择父类内部的类
- 访问JSON对象内部的数组元素
- 从模块内部访问Express装载路径
- AngularJs指令,该指令创建内部有数据对象的新指令
- 如何使用内部对象构造对象
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 用Javascript修改内部标记的CSS规则
- Javascript书签按钮
- javascript函数内部的代码用逗号而不是分号分隔
- 正在$rootScope上达到控制器作用域$在内部控制器上
- 光线投射从内部投射时不会碰到网格
- 对特定的iframe使用javascript书签
- javascript无法重新定义函数内部的全局对象
- 在不移动内部文本的情况下缩放元素的效果
- 从书签内部关闭书签
- 如何创建一个内部带有延迟/超时的 javascript 书签