开发者

Can a function defined in a bookmarklet be called from a page-level script?

I have a bookmarklet that needs to open a new window/tab. In order to avoid the popup blocker, I need to call the window.open() method directly in the bookmarklet ie: at the browser-level.

However, I want to keep the b开发者_开发技巧ookmarklet updatable by loading external Javascript files. To do this, the bookmarklet needs to append script nodes to the DOM. If i were to put window.open() code in one of these externally loaded scripts, the popup blocker would block it since its page-level.

What I want to know is if I can create a wrapper function around window.open() in my bookmarklet, then call it from the externally loaded script? What is the scope and what are the permissions on a wrap such as this?


I came up with a solution which isn't perfect but meets the requirements:

Here is the bookmarklet code:

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);

The readable step-by-step equivalent being:

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

Only one issue remains: the page you want to show isn't active by default. The cloned one is.


I wondered if that approach might work - good to see that it does.

The general problem here is that browsers will not let you open a new window other than by direct user interaction. So you cannot open the window from a remote script.

You are opening the window directly from the bookmarklet, moving to that location and then invoking the remote script.

The alternative, which I went with, was to move the contents of the remote script directly to the bookmarklet. That was fine for my simple application. I wrote up that on my blog

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜