zhm
zhm

Reputation: 3641

Why this code generate a link?

This code snap:

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

Open it in Chrome, click link Open "prompt" dialog, then click OK. It will generate a link in current web page. Why?

I see document of prompt(). It says prompt() returns a string which user inputs in, in this case: <a href=javascript:window.close();> Close me </a >.

I tried to replace href in the code to the return value of prompt():

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

Then the link failed to open with error: Your file was not found.

Could someone explain this?

Upvotes: 1

Views: 99

Answers (1)

shaochuancs
shaochuancs

Reputation: 16226

This has nothing to do with window.prompt() or target="new", it is due to javascript: protocol's behavior. I've made a simplified example below:

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

In the above example, when click_me is clicked, the page content will be wiped out and only display text result_content, no content_ahead span and no click_me link any more.

Explanation:

  1. When click_me is clicked, browser will execute javascript program defined by javascript: protocol.
  2. After the execution, if a String is returned, the browser will take it as the content of "new page" and "open" it. Anyway, it's the same logic as href to http: or https:// -- fetch data and display it as new page. You can take this experiment in Firefox, where even the address bar is changed to javascript://(function(){return 'result_content'})().
  3. After the execution, if no String is return, there is no content for the "new page". Browser will keep displaying the old one.

For reference, here is an old article describing the javascript statement in javascript: URL:

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.

Upvotes: 4

Related Questions