开发者

javascript - How do I make onclick"window.location" also work when user opens in new window

To hide the true destination of a link I'm using the following code:

<a href="http://example.com" onclick="window.location='http://url-i-want-to-hit.开发者_如何学编程com/'; return false;">Click me</a>

However, if I do right-click and then open in new window, it goes to the url specified in the anchor href tag. I want it to go to the url specified in the javascript.

Is there a way to do this?

Thanks in advance


All you need is a mousedown handler to fake them out...

<a href="http://example.com"
   onmousedown="this.href2 = this.href;
                this.href = 'http://url-i-want-to-hide.com/';"
   onmouseout="if(this.href2) this.href = this.href2;">Test</a>

And here is a live demo of it working.


However, if I do right-click and then open in new window, it goes to the url specified in the anchor href tag. I want it to go to the url specified in the javascript.

No, but you could use JS to set the link href to the hidden URL after the document has loaded (or in the onfocus and onhover events of the link, although that feels rather kludgy and incomplete).

<a onfocus="this.href='hidden_url'" .....>

this is the way Google use to count outgoing links from the search results page.


You can't do this. Right click uses the true anchor, whereas you are overriding the click functionality of the anchor with javascript. A bit deceptive aren't we?


How about storing the real urls in a database and calling them in php?

www.yourwebsite.com/url.php?id=3

url.php // something like

$query = "SELECT * FROM `urls` WHERE `id` = " . intval($_GET['id']);
$row = mysqli_fetch_assoc($query);

header ("location: $row['url']");


EDIT: Maybe I wasn't clear...sorry. Using an "#" would prevent them opening a different page in a new window. This may not work for your situation, and I don't know if you are trying to get something accomplished with SEO by hidding the URL. My solution is virtually the same as what you are currently doing except for the "#" in the href and I just prefer to have the window.location wrapped in a function....personal preference.

<a href="#" onclick="SendToUrl(); return false;"">Click Here</a>


<script language="javascript">
   function SendToUrl(){
       window.location='http://url-i-want-to-hide.com/'
    }
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜