有另一种绕过弹出窗口拦截器的方法,可以先在页面上叠加一个链接,然后允许用户单击该链接生成弹出窗口。书签脚本JavaScript可以存储在单独的文件中。这就是Pinterest的书签脚本如何实现的。首先,他们从页面中选择图像并直接覆盖在页面上。然后,当用户点击选择其中一张照片时,弹出窗口会出现。因为此操作是由用户发起的,所以弹出窗口有效。
以下是可用于测试的代码:
将此代码放入名为bookmarklet.js的文件中:
var popupProperties='width=600,height=400,toolbar=0,location=0,resizable=1';
var newA = document.createElement("a");
var url = 'http://www.stackoverflow.com';
newA.setAttribute("href","javascript:window.open(url,'Hi',popupProperties);");
newA.setAttribute("style","position:fixed;z-index:9999999;top:0;left:0;width:100px;height:100px;color:#000;background:#fff;display:block;");
var newT = document.createTextNode("Open this");
newA.appendChild(newT);
document.body.appendChild(newA);
然后你的书签链接可以像这样:
javascript:var jsCode = document.createElement('script');jsCode.setAttribute('src', 'http://localhost/bookmarklet.js?r='+Math.random()*99999999);document.body.appendChild(jsCode);
或者,你需要将弹出窗口包含在实际的书签链接中。这意味着用户要进行任何更改,唯一的方法就是重新安装书签。
编辑:除了上面的方法,我后来发现使用easyXDM甚至有另外一种绕过此问题的方式。它可以帮助你绕过同源策略。 http://easyxdm.net/wp/
使用它,你可以为你的书签使用一个iframe,甚至可以在你的iframe内部拥有一个“关闭”链接,以便能够从父页面中删除iframe。