Cannot trigger click event [duplicate] - javascript

I have a anchor link like
<a id="myanchor" href="http://google.com" target="_blank">Google</a>
How to open href target in a new tab programatically?

Try the following:
$("#myanchor")[0].click()
As simple as that.

There's a difference in invoking the click event (does not do the redirect), and navigating to the href location.
Navigate:
window.location = $('#myanchor').attr('href');
Open in new tab or window:
window.open($('#myanchor').attr('href'));
invoke click event (call the javascript):
$('#myanchor').click();

Even though this post is caput, I think it's an excellent demonstration of some walls that one can run into with jQuery, i.e. thinking click() actually clicks on an element, rather than just sending a click event bubbling up through the DOM. Let's say you actually need to simulate a click event (i.e. for testing purposes, etc.) If that's the case, provided that you're using a modern browser you can just use HTMLElement.prototype.click (see here for method details as well as a link to the W3 spec). This should work on almost all browsers, especially if you're dealing with links, and you can fall back to window.open pretty easily if you need to:
var clickLink = function(linkEl) {
if (HTMLElement.prototype.click) {
// You'll want to create a new element so you don't alter the page element's
// attributes, unless of course the target attr is already _blank
// or you don't need to alter anything
var linkElCopy = $.extend(true, Object.create(linkEl), linkEl);
$(linkElCopy).attr('target', '_blank');
linkElCopy.click();
} else {
// As Daniel Doezema had said
window.open($(linkEl).attr('href'));
}
};

window.open($('#myanchor').attr('href'));
$('#myanchor')[0].click();

It worked for me:
window.location = $('#myanchor').attr('href');

$(":button").click(function () {
$("#anchor_google")[0].click();
});
First, find the button by type(using ":") if id is not given.
Second,find the anchor tag by id or in some other tag like div and $("#anchor_google")[0] returns the DOM object.

You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here

Related

Change link target to "_self" for existing Click eventListener (which currently targets "_blank")

I am writing a userscript for a website to change link targets from "_blank" to "_self".
The website's links are all handled by an EventListener on Click action, which reviews the id attribute for every <a> element to set the click URL and load it in a new tab. None of the <a> elements have a href or target attribute.
I would like all clicked links to load in the same tab (rather than a new tab).
Is there any way to modify link targets set by an event listener, or to simply set/override the default link target for all links on a webpage?
Provided you want to override the behavior of links that open in a new tab, you could override window.open as such:
window.open = (open => (href => open.call(window, href, '_self')))(window.open);
For anchor tags with an explicit target of _blank, you could theoretically override the click method to force the target:
window.HTMLAnchorElement.prototype.click = function() { window.open(this.href, '_self') };
However, this is in fact a hacky solution and might not be the best idea to use in production.
you can do select your element with document.querySelector().target = "_self"
EDIT Jan 12, 2023: there is a much better and easier way to do this, if you're using Tampermonkey.
GM_addElement allows you to do exactly what I described in the request, to insert code into actual page:
https://www.tampermonkey.net/documentation.php#api:GM_addElement
I used the script version, to add a function (you have to enclose it in quotes, like text).
This solution works much better with stricter websites and browsers, so you won't get CSP errors.
OLD ANSWER:
The answer to this question solved my issue:
How to overwrite a function using a userscript?
I re-wrote the open function from skara9's answer, and then inserted it with the addJS_Node function from the above question.
Userscripts are separated from the target page, hence why simply re-declaring the function was not overwriting the default global open function.

Javascript Window.Open Opens the Target URL in Both a New Window and the Same

Basically, I have a page with social media share buttons. Some of them work as they should (they open up in a new window), however, others open up both in a new window and in the same window. I have been going crazy for a day now over this and I cannot seem to find a way to fix it.
For reference, this is the page: http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/
Link that works as expected (Facebook, Twitter, Pinterest):
<a href="javascript:void(0)" class="ism_link" onclick="indeedPinterestPopUp(2513);ism_fake_increment('.pinterest_share_count', 'pinterest', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');">
Link that opens the URL to share in both a new window and in the same:
<a href="http://www.stumbleupon.com/badge/?url=http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/&title=GSA%20Search%20Engine%20Ranker%20Ultimate%20Tutorial%20and%20Genuine%20Review%20%E2%80%93%20SEO%20Software%20of%20the%20Gods" class="ism_link" onclick="ism_fake_increment('.stumbleupon_share_count', 'stumbleupon', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');return !window.open(this.href, '', 'width=700,height=575');">
What I have tried:
I have tried to remove the "href" attribute of the tag and insert the URL string into the window.open function instead of using "this.href". When I do that, the link opens only a new window, but doesn't open the share page of the respective social media, but rather, the target URL.
I have tried to add "return false" after the non-working window.open function.
I have also tried to remove the "ism_fake_increment" function just to test, but again, to no avail.
I have contacted the plugin author, but they requested to access my website internally, which is not going to happen.
Any ideas will be strongly appreciated. Thank you for your time!
I advise that you don't use the onclick attribute because it leads to extremely messy code. Instead, use the .addEventListener() in the DOM.
To disable the link from opening the link in the same window, just disable the default even. This can be done with .addEventListener() in the callback by calling the .preventDefault() method of the object passed into the callback:
//Get our link:
var link = document.getElementById("stumbleupon");
//Bind the click event:
link.addEventListener("click", function(event) {
//Prevent the link from opening regularly with .preventDefault():
event.preventDefault();
//The following code with the plugin does not work because we haven't included the plugin in the code snippet, but as you can clearly see if you click the link, the link has clearly been disabled because of the above call to .preventDefault().
//Do different stuff with the plugin:
ism_fake_increment('.stumbleupon_share_count', 'stumbleupon', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');
return !window.open(this.href, '', 'width=700,height=575');
});
<!-- Set the ID attribute so we can find this link in the DOM: -->
<a id="stumbleupon" href="http://www.stumbleupon.com/badge/?url=http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/&title=GSA%20Search%20Engine%20Ranker%20Ultimate%20Tutorial%20and%20Genuine%20Review%20%E2%80%93%20SEO%20Software%20of%20the%20Gods" class="ism_link">Hello! This is a link to stumbleupon.com!</a>

How to use target in location.href

I am currently developing a web application where I need to open a popup window to show a report. The problem is that some versions of explorer don't support the window.open javascript function, so when this is the case I catch the error and open the new url with location.href. Here the code:
try {
window.open(url, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
} catch(e) {
location.target = "_blank";
location.href = url;
}
The problem is that the location.target is not working and I would like to know if there is a way to specify the target of the location.href so it can be opened in a new tab.
try this one, which simulates a click on an anchor.
var a = document.createElement('a');
a.href='http://www.google.com';
a.target = '_blank';
document.body.appendChild(a);
a.click();
You can use this on any element where onclick works:
onclick="window.open('some.htm','_blank');"
The problem is that some versions of explorer don't support the window.open javascript function
Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.
Most modern browsers won't let your code use window.open except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open when responding to a user event, you should be fine using window.open — with all versions of IE.
There is no way to use location to open a new window. Just window.open or, of course, the user clicking a link with target="_blank".
If you go with the solution by #qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.
// Code by #qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)
Maybe someone could post a comment to his post, because I cannot.
You could try this:
<script type="text/javascript">
function newWindow(url){
window.open(url);
}
</script>
And call the function
If you are using an <a/> to trigger the report, you can try this approach. Instead of attempting to spawn a new window when window.open() fails, make the default scenario to open a new window via target (and prevent it if window.open() succeeds).
HTML
Link
JS
var spawn = function (e) {
try {
window.open(this.href, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
e.preventDefault(); // Or: return false;
} catch(e) {
// Allow the default event handler to take place
}
}
document.getElementById("myLink").onclick = spawn;
Why not have a hidden anchor tag on the page with the target set as you need, then simulate clicking it when you need the pop out?
How can I simulate a click to an anchor tag?
This would work in the cases where the window.open did not work
As of 2014, you can trigger the click on a <a/> tag. However, for security reasons, you have to do it in a click event handler, or the browser will tag it as a popup (some other events may allow you to safely trigger the opening).
jsFiddle
<input type="button" value="fake button" />

I need to open a new window in the background with JavaScript, and make sure the original is still focused

I have a window I'm opening with a Javascript function:
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
}
I need it that once the new window opens that the focus returns to the original window.
How can I do that?
And where do I put the code - in the new window, or the old one?
Thanks!
This is known as a 'pop-under' (and is generally frowned upon... but I digress).. It should give you plenty to google about
You probably want to do something like:
var popup = window.open(...);
popup.blur();
window.focus();
Which should set the focus back to the original window (untested - pinched from google). Some browsers might block this technique.
After calling window.open, you may try to use
window.resizeTo(0,0);
window.moveTo(0,window.screen.availHeight+10);
this way can not really open window in background, but works in similar way. Chrome works fine, did not try other browser.
If Albert's solution doesn't work for you and you actually want the window visible, but to be opened behind the current window, you can try opening a new tab in the opener window and closing it right away, this will bring the focus back to the opener window.
window.open('link.html','','width=,height=,resizable=no');
window.open().close();
However, I believe whether the second window opens in a tab or a new window depends on your browser settings.
Please don't use "pop-unders" for evil.
You can use either
"blur" or
"focus" to do that required action.
"blur"
function newwindow()
{
var myChild= window.open('link.html','','width=,height=,resizable=no');
myChild.blur();
}
"focus"
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
window.focus();
}
Put the code in your parentWindow (i.e. the window in which you are now)
Both will work.
tl;dr - in 2022 - ctrl/cmd clicking on a button and window.open(url, "_blank") in a javascript button handler's for loop will open multiple tabs in the background in Chrome.
I'm looking for this as of 2022 and none of the answers here worked (here and everywhere else I looked). My use case is clicking a button in a (progressive) web app which opens deep links to items in a list in background tabs (i.e. not "for evil").
It never occurred to me that ctrl/cmd + clicking on the button would open tabs in the background, but it does just as if the user clicked on an anchor tag itself directly - but only in Chrome. Combined with Chrome's relatively recent tab grouping feature, this can be very useful inside PWAs.
const isMozilla =
window?.navigator?.userAgent?.toString().toLowerCase().includes('firefox') ?? false;
for (let index = 0; index < urls.length; index++) {
const url = isMozilla ? urls.reverse()[index] : urls[index];
window.open(url, "_blank");
}
Note: I reverse() the array on Mozilla to get the order of newly created tabs as the user would expect them.
You can just use '_self'. It will be stay to the same page an
window.open(url, '_self');

What's the best way to open new browser window?

I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).
What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.
I know that <a href="url" target="_blank"> is out. I also know that <a href="#" onclick="window.open(url);"> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <span onclick="window.open(url);"> and then style the SPAN to look like a link.
One solution I'm leaning towards is <a href="url" rel="external"> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.
Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.
UPDATE: I say target="_blank" is a no no, because I've read in several places that the target attribute is going to be phased out of XHTML.
I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:
$(document).ready(function() {
$('a[rel*=external]').click(function(){
window.open($(this).attr('href'));
return false;
});
});
I find this the best method because:
it is very clear semantically: you have a link to an external resource
it is standards-compliant
it degrades gracefully (you have a very simple link with regular href attribute)
it still allows user to middle-click the link and open it in new tab if they wish
Why is target="_blank" a bad idea?
It's supposed to do exactly what you want.
edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)
Please, don't force opening a link in a new window.
Reasons against it:
It infringes the rule of the least astonishment.
The back-button don't work and the user not possibly knows why.
What happen in tabbed browsers? New tab or new window? And whichever happens, is it what you wants, if you mix tabs and windows?
The reason I always hear in favor of opening a new window is that the user will not leave the site. But be sure, I will never come back to a site that annoys me. And if the site takes away control from me, that is a big annoyance.
A way may be, that you give two links, one is normal, the other opens it in a new window. Add the second with a little symbol after the normal link. This way users of your site stay in control of which link they want to click on.
Here is a plugin I wrote for jQuery
(function($){
$.fn.newWindow = function(options) {
var defaults = {
titleText: 'Link opens in a new window'
};
options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
if (options.titleText) {
if (obj.attr('title')) {
var newTitle = obj.attr('title') + ' ('
+ options.titleText + ')';
} else {
var newTitle = options.titleText;
};
obj.attr('title', newTitle);
};
obj.click(function(event) {
event.preventDefault();
var newBlankWindow = window.open(obj.attr('href'), '_blank');
newBlankWindow.focus();
});
});
};
})(jQuery);
Example Usage
$('a[rel=external]').newWindow();
You can also change, or remove the title text, by passing in some options
Example to change title text:
$('a[rel=external]').newWindow( { titleText: 'This is a new window link!' } );
Example to remove it alltogether
$('a[rel=external]').newWindow( { titleText: '' } );
Perhaps I'm misunderstanding something but why don't you want to use target="_blank"? That's the way I would do it. If you're looking for the most compatible, then any sort of JavaScript would be out as you can't be sure that the client has JS enabled.
link text
Details are described in my answer to another question.
<a href="http://www.google.com" onclick="window.open(this.href); return false">
This will still open the link (albeit in the same window) if the user has JS disabled. Otherwise it works exactly like target=blank, and it's easy to use as you just have to append the onclick function (perhaps by using JQuery) to all normal tags.
If you use any flavor of strict doctype or the coming real xhtml-flavors, target isn't allowed ...
Using transitional, whatever being HTML4.01 or XHTML1, you can use Damirs solution, though it fails to implement the windowName-property which is necessary in window.open():
In plain html:
link
If however you use one of the strict doctypes your only way of opening links would be to use this solution without the target-attribute ...
-- by the way, the number of non-js-browsers is often miscalculated, looking up the counters numbers refer very different numbers, and I'm wondering how many of those non-js-browsers is crawlers and the like !-)
If I'm on a form page and clicking on a moreinfo.html link (for example) causes me to lose data unless I open it in a new tab/window, just tell me.
You can trick me in to opening a new tab/window with window.open() or target="_blank", but I might have targets and pop-ups disabled. If JS, targets and pop-ups are required for you to trick me into opening a new window/tab, tell me before I get started on the form.
Or, make links to another page a form request, so that when the visitor submits, the current form data is saved so they can continue from last time, if possible.
I use this...
$(function() {
$("a:not([href^='"+window.location.hostname+"'])").click(function(){
window.open(this.href);
return false;
}).attr("title", "Opens in a new window");
});

Categories