Reputation: 3641
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
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:
click_me
is clicked, browser will execute javascript program defined by javascript:
protocol.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'})()
.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