Intercept right-click on URL with jQuery
I'm developing a site that uses ajax to load content in, but I also provide semantic links to the actual ajax page for browsers with JS disabled:
<a href="/products/car.html">Show Cars</a>
$("a").click(function(){
$("#main").load('/products/car.html');
return false;
});
If a user right-clicks/command-clicks and copies the UR开发者_运维知识库L (www.mysite.com/products/car.html
) to share with a friend, is there a way for me to intercept that link in jQuery and exceute a function?
if window.location == 'www.mysite.com/products/car.html' > Do This
?
why not?
if (window.location.href == 'http://mysite.com/products/cars.html')
{
doSomething ();
}
You can't prevent the user from manually typing in a new URL in their browser bar via JavaScript.
However, in your car.html source, (you'd probably need car.php or something instead, depending on your server side code), you could test the request headers to determine the "Accepts" value.
- If it's something like "text/javascript" or "application/json", then simply send the JSON content as you normally would.
- If it's something else (like "text/html"), then redirect them to this page that loads the JSON content, with the car.html content as the default-loaded content.
Edit: I might have misunderstood a bit. When the car.html page loads, there's nothing to stop you from executing JavaScript on page load to check the current URL & redirect the user elsewhere.
精彩评论