I the below script, once the button is pressed, a new browser tab with Google is opened. I then want to fill the search box on this newly opened tab.
How do I switch focus to this new tab, so that I can wait for it to load completely and then fill the search box?
<button id="start">Google</button>
<script>
function open_google_in_new_tab() {
var url = "https://www.google.com";
window.open(url);
window.onload(fill_search_box()); // here it will try to operate on the old tab
};
function fill_search_box() {
var search_box = document.getElementsByName("q")[0];
search_box.value = "Some text";
};
var start_button = document.getElementById("start");
start_button.addEventListener("click", open_google_in_new_tab);
</script>
You can't exactly target another element in another document from your script, however, you can set the textbox value of the Google textbox using a query string:
www.google.com?q=SearchTerm
When creating the SearchTerm you should also use encodeURI to ensure that your attached search query meets URL standards
Also, if you wish to open the window in another tag you can use window.open(url, "_blank") to open.
See example below:
Note:- The page will not open due to snippet restrictions - so run in your own browser.
<button id="start">Google</button>
<script>
function open_google_in_new_tab() {
var text = "Some text";
var url = "https://www.google.com?q=" + encodeURI(text);
console.log(url)
window.open(url, '_blank');
};
var start_button = document.getElementById("start");
start_button.addEventListener("click", open_google_in_new_tab);
</script>
You cannot do that with Javascript unfortunately.
However, this might make you achieve something similar if you are willing to try.
You can manipulate the search string via parameter named "q" in the query string of the Google website. So, in order to make the user to go the Google and search this particular word, you attach the keyword to it. Something like this:
var url = "https://www.google.com?q=searchKeyword";
Related
I wanted to make the tag open two URLs at the same time. This is what I tried:
Only HTML
text
This did work but not the way I wanted it to. It would open the URL2 when clicked on it and if opened in a new tab with right click or the mouse wheel it would open URL1. I want it to open both pages in new tabs at the same time.
HTML + JavaScript
HTML:
<a id="myId">text</a>
JS:
myId.onclick = function(){
open('https://www.example1.com');
location.href = ('https://www.example2.com');
}
This didn't work at all.
This is Your code :
myId.onclick = function(){
open('https://www.example1.com');
location.href = ('https://www.example2.com',,'_blank');
}
Change the code to:
myId.onclick = function(){
window.open('https://www.example1.com','_blank'); //just use window.open() for both the cases;
window.open('https://www.example2.com','_blank');
}
Hope, you have got the solution for your problem.
As per your requirement, I would suggest following.
Also look at the fiddle HERE
Open Two URLs
var myId = document.getElementById("myId");
myId.onclick=function(){
window.open("https://www.google.com","_blank");
window.open("https://www.microsoft.com","_blank");
}
You should be allowing your browser's POPUP BLOCKER to allow opening multiple pages/tabs for this to work.
Try using an onclick function that uses window.open to open the two URLs:
document.querySelector("#foo").onclick = function () {
window.open("https://www.example.com", "_blank");
window.open("https://www.example.com", "_blank");
};
<a id="foo">bar</a>
Code:
button = document.getElementById('button');
function buttonPress(){
input = document.getElementById('input');
url = input.value;
console.log(url);
let a = window.open(url,"name");
a.focus();
setTimeout(console.log("wait until confirm"),4000);
if(confirm('Start download?')){
alert('Downloading');
}
else{
alert('Why you no love me...');
window.close;
}
}
button.addEventListener("click",buttonPress)
The problem is that the confirm opens in the previous tab, not in the new one. I've tried with location.replace or href but it still doesn't work. Any ideas how I could get there?
this happens because the code you wrote is running in the previous page.
therefore, any function that you will use will write and call in this javascript snippet will run inside the previous page.
to solve this problem, you can add the confirm function in the javascript section of the url which you open.
I am using this bit of jQuery code to get href of the link:
var url = $(this).attr('href');
-- and this bit of code to go to that href:
window.location = url;
Everything is just the way I want it, except the new page opens in the same window as the previous one, and I want it to open in a new window or tab (something that in plain html would have been achieved by using target="_blank" formula).
Question: How can I open the href in the new window or tab with jQuery?
Thank you for your help!
You need to open a new window:
window.open(url);
https://developer.mozilla.org/en-US/docs/DOM/window.open
Use,
var url = $(this).attr('href');
window.open(url, '_blank');
Update:the href is better off being retrieved with prop since it will return the full url and it's slightly faster.
var url = $(this).prop('href');
Question: How can I open the href in the new window or tab with
jQuery?
var url = $(this).attr('href').attr('target','_blank');
The .ready function is used to insert the attribute once the page has finished loading.
$(document).ready(function() {
$("class name or id a.your class name").attr({"target" : "_blank"})
})
Detect if a target attribute was used and contains "_blank". For mobile devices that don't like "_blank", this is a reliable alternative.
$('.someSelector').bind('touchend click', function() {
var url = $('a', this).prop('href');
var target = $('a', this).prop('target');
if(url) {
// # open in new window if "_blank" used
if(target == '_blank') {
window.open(url, target);
} else {
window.location = url;
}
}
});
If you want to create the popup window through jQuery then you'll need to use a plugin. This one seems like it will do what you want:
http://rip747.github.com/popupwindow/
Alternately, you can always use JavaScript's window.open function.
Note that with either approach, the new window must be opened in response to user input/action (so for instance, a click on a link or button). Otherwise the browser's popup blocker will just block the popup.
Try using the following code.
$(document).ready(function(){
$("a[#href^='http']").attr('target','_blank');
});
url='/controller/action';
window.open(location.origin+url,'_blank');
I have a question about the new tab for the link.
Is there anyway I can set the browser tab title before user clicks a link? It seems like there is no way to debate the title for the new tab if the html contained in the new tab doesn't have title attribute. Am I right? How do I set the title?
//the href is dynamic so I can't set them one by one because I have 100+ html file here
<a href="test.html" target="_blank">open me<a>
As you have it, this is not possible because your links are just normal HTML links. When the new page opens in a new tab, the current page will not have any reference to it and so cannot change it in any way. You will need to open the page using javascript and set the title that way.
You can dynamically set this up in window onload to find all a tags and add a click event whihc opens the window and sets the title.
If you want different titles for each page, you can store this in a data- attribute in the a tag.
Note tho that this will only work with pages in the same domain (for security), and that it does not handle people right clicking and pressing "Open in New Window". Middle click in Windows does seem to work however.
HTML
open me
JavaScript
window.addEventListener("load", function() {
// does the actual opening
function openWindow(event) {
event = event || window.event;
// find the url and title to set
var href = this.getAttribute("href");
var newTitle = this.getAttribute("data-title");
// or if you work the title out some other way...
// var newTitle = "Some constant string";
// open the window
var newWin = window.open(href, "_blank");
// add a load listener to the window so that the title gets changed on page load
newWin.addEventListener("load", function() {
newWin.document.title = newTitle;
});
// stop the default `a` link or you will get 2 new windows!
event.returnValue = false;
}
// find all a tags opening in a new window
var links = document.querySelectorAll("a[target=_blank][data-title]");
// or this if you don't want to store custom titles with each link
//var links = document.querySelectorAll("a[target=_blank]");
// add a click event for each so we can do our own thing
for(var i = 0; i < links.length; i++) {
links[i].addEventListener("click", openWindow.bind(links[i]));
}
});
Sample JsFiddle
You can pass the title with hash and get it on another page, if this another page is yours and you can modify its code.
1st page:
...
<a href="test.html#the_title_you_want" target="_blank">open me<a>
...
2nd page - modify the body opening tag like this:
<body onload="document.title=window.location.hash.replace('#','');">
If the page you are linking to isn't yours, you can use window.open method:
open me
I have not seen addEventListener work reliably, especially when opening a new page using javascript. The best way to change the tab title and have it work reliably is to set a timeout until the page loads. You may have to play with the timeout value, but it works.
var newWindow = window.open(url, '_blank');
setTimeout(function () {
newWindow.document.title = "My Tab Name";
}, 100);
You have two options. Using pure HTML, you can let the user open up links, then later on change the title. Or you can change the title with inline JavaScript. Here's how you do both:
Method 1
Change your links by assigning a target attribute, and then later on use that window name to control the document. For instance in your links it would be: <a href="whatever" target="theNewWindow">. Whenever you want to change the title for this page, you'd use JavaScript as such: window.open("", "theNewWindow").document.title = "New Page Title!"; The problem with this method however is that all links with that target/window name will open in that same window. In addition, after the first time the link is clicked, your browser won't automatically switch to the new tab/window.
Method 2
Change your links by assigning an onclick attribute, which would open the link manually and change the title of the page immediately. Basically it would come down to look like: <a href="whatever" onclick="var w=window.open(this.href, '_blank'); (w.onload=function(){w.document.title='New Page Title!';})(); return false;">. This opens the window based on the href attribute, immediately changes the title, and sets the window to change the title to that when it finishes loading (just in case there really was a title tag).
The problem with both of these methods (as mentioned by others) is your html files have to be on the same domain.
The simplest way is a follows:
var winTab = window.open("", "_blank")
//Open URL by writing iframe with given URL
winTab.document.write("write iframe with your url in src here")
//Set Title for the new tab
winTab.document.title = "Form Title"
You could make your own Page 2 that opens up the other pages (the ones you can't edit), in a frameset. You can then either change the title dynamically when loading your page 2, or as others have suggested if you use window.open you can control the title from the parent page.
If you are in page 1, and opening page 2 in a new tab, you can't set title for page 2 from page 1.
If you have access to page 2 then it's possible, otherwise not.
I have written a script that opens a pop up window , searches for a user , when finds
the user the search window closes and then the script shows the new user in the parent window.
Basically I tried all of the script separately but I have problems when I pass between windows. The code ahead does not pass the found user, but passes one example user just for meantime to debug the code.
Here is the script file: ( I will explain it later )
var orgWindow
var searchWindow
$(document).ready(function(){
$(".add_participants").on("click", function() {
var orgWindow = window.self
var searchWindow = window.open("http://localhost:3000/users/search", "_blank",
"left=200, top=100, height=300, width=300, menubar=yes");
});
});
function printUser(){
var a = orgWindow.document.createElement("a");
a.setAttribute("href","/users/show");
a.setAttribute("id","3");
var aText = orgWindow.document.createTextNode("elad bezalel");
var img = orgWindow.document.createElement("img");
img.setAttribute("alt","El4");
img.setAttribute("src","/uploads/user/image/3/el4.jpg");
img.setAttribute("height","150");
img.setAttribute("width","150");
myDiv = orgWindow.document.getElementById("par");
a.appendChild(img);
var brk = orgWindow.document.createElement("br");
a.appendChild(brk);
a.appendChild(aText);
myDiv.appendChild(a);
}
function add_user(){
user_id = $("#button").data("user_id");
window.close(searchWindow);
window.blur(searchWindow);
window.focus(orgWindow);
orgWindow.document.write(printUser());
orgWindow.close();
}
I am using jQuery. when I click a button the search window open. Then I find a user in the search window and click on another button (add user) and then the search window closes and the parent window gets focused. Now I tried to implement the user image and name, but somehow it doesn't work.
How should I repair my script?
Note that you have declared orgWindow and searchWindow as variables in two different scopes, the global scope (the two var usages at the top) and local to the click handler. This could be part of your problem.
I think the two separate window contexts are getting intermingled.
In the main page add_user function:
function add_user(user_id){
window.close(searchWindow);
window.blur(searchWindow);
window.focus(orgWindow);
orgWindow.document.write(printUser());
orgWindow.close();
}
And in the popup:
$("#button").click($(window.opener).add_user($(this).data("user_id")));