为什么此代码生成 link?

Why this code generate a link?

这段代码快照:

<a href="javascript:window.prompt('Press OK button to insert this link in the new window ...', '<a href=javascript:window.close();> Close me 
            </a >')" target="new">
        Open "prompt" dialog
</a>

在Chrome中打开它,点击link Open "prompt" dialog,然后点击OK。它将在当前网页中生成一个link。为什么?

我看prompt()的文档。它说 prompt() returns 用户输入的字符串,在这种情况下:<a href=javascript:window.close();> Close me </a >.

我尝试将代码中的href替换为prompt()的return值:

<a href="'<a href=javascript:window.close();> Close me </a >'" target="new">
    Open "prompt" dialog
</a>

然后 link 无法打开错误:找不到您的文件

有人可以解释一下吗?

这与 window.prompt()target="new" 无关,这是由于 javascript: 协议的行为。我在下面做了一个简化的例子:

<span>content_ahead</span>
<a href="javascript:(function(){return 'result_content'})()">
  click_me
</a>

在上面的例子中,当点击click_me时,页面内容将被清除,只显示文本result_content,没有content_ahead span,没有click_me link 了。

解释:

  1. 当点击click_me时,浏览器将执行javascript由javascript:协议定义的程序。
  2. 执行后,如果一个String被return编辑,浏览器会将其作为"new page"和"open"的内容。无论如何,它与 hrefhttp:https:// 的逻辑相同——获取数据并将其显示为新页面。您可以在 Firefox 中进行此实验,甚至地址栏也更改为 javascript://(function(){return 'result_content'})().
  3. 执行后,如果没有String是return,则没有"new page"的内容。浏览器将继续显示旧版本。

作为参考,这里有一个旧的 article 描述了 javascript: URL 中的 javascript 语句:

The JavaScript statement used in a javascript: URL should not return any value. For example, the alert() method doesn't return a value; in other words, it returns undefined. If the statement returns undefined, the browser simply executes it. However, if it returns an explicit value, the browser loads a new page, with the javascript: URL in the Location bar, and the returned value in the body of the page.