像<a> tag in a Bookmarklet

时间:2018-12-30 01:06:43

标签: javascript bookmarklet

Just to explain my specific use for it; I made a really simple bookmarklet to open the equalivalent explainxkcd page from any xkcd comic. It looks like this:

javascript:a=new URL(location);a.host==="xkcd.com"&&(a.host="explain"+a.host,open(a))

unminified:

let url = new URL(location);
if (url.host === "xkcd.com") {
    url.host = "explain" + url.host;
    open(url) # I want this to open "dynamically" like an <a> tag instead
}

By open like an <a> tag, I mean replace the current tab(_self) if the ctrl key isn't held, otherwise open in a new tab(_blank) if ctrl is held. Approaches I've thought of:

  • Check event.ctrlKey and use that to pass in "_self" or "_blank", but unfortunately, it's not in an event...

  • Add a link to the page programatically and then click it. This just feels really hacky.

  • Add a keydown and keyup event and track whether the ctrl key is down, but that doesn't work in a bookmarklet.

Is there some bookmarklet only way to do this, or some method I've overlooked?

1 个答案:

答案 0 :(得分:0)

编辑:
由于无法确定是按下Ctrl键还是基于该键改变行为,因此无法避免其他不太理想的解决方案。

一个例子:

javascript:void%20function(){if(%22xkcd.com%22===location.host){var%20o=%22https://explain%22+location.host.toString()+location.pathname.toString(),n=confirm(o+%22%20to%20be%20openend%20in%20new%20tab%22);n%3Fwindow.open(o,%22_blank%22):window.location.replace(o)}}();
  • 触发提示
  • 取消/退出:当前窗口/标签页
  • 确定/输入/空格:新标签页

您的“流程”将变为:单击书签,然后立即进行转义,或者根据是否应在新标签页中打开进行输入。