可以从页面级脚本调用小书签中定义的函数吗?

时间:2010-01-23 20:37:37

标签: javascript permissions popup wrapper bookmarklet

我有一个需要打开新窗口/标签的书签。为了避免弹出窗口阻止程序,我需要直接在bookmarklet中调用window.open()方法,即:在浏览器级别。

但是,我希望通过加载外部Javascript文件来保持书签可更新。为此,小书签需要将脚本节点附加到DOM。如果我将window.open()代码放在其中一个外部加载的脚本中,弹出窗口阻止程序会阻止它自页面级别。

我想知道的是我是否可以在我的书签中创建window.open()周围的包装函数,然后从外部加载的脚本中调用它?什么是范围以及对此包装的权限是什么?

2 个答案:

答案 0 :(得分:1)

我想出了一个不完美但符合要求的解决方案:

这是小书签代码:

javascript:window.open(window.location);window.location="http://www.google.com/";var%20s=document.createElement('script');s.setAttribute('src','http://my-script.js');document.body.appendChild(s);void(0);

可读的逐步等同于:

window.open(window.location);                // Clone the current tab
window.location = "http://www.google.com/";  // Navigate to the desired page url
var s = document.createElement('script');    // Create the script
s.setAttribute('src','http://my-script.js'); //
document.body.appendChild(s);                // Embed it into current document

只剩下一个问题:默认情况下,您要显示的页面无效。克隆的是。

答案 1 :(得分:0)

我想知道这种方法是否有用 - 很高兴看到它。

这里的一般问题是浏览器不允许您通过直接用户交互打开新窗口。因此,您无法从远程脚本打开窗口。

您正在直接从书签中打开窗口,移动到该位置,然后调用远程脚本。

我选择的另一种方法是将远程脚本的内容直接移动到书签。这对我的简单应用来说很好。我写了on my blog