I'd like to access an element in a new tab and write a value to it.
I created a site (html) with different buttons, which start a javascript, which will open the new tab and should look for specified element by id in the new tab.
When it's found, it should enter e.g. a username.
But it never finds the element in the the new tab. I guess the focus still is on the first document.
How can I change the focus of the javascript to the new tab?
CodePudding user response:
You can open the window and save it to a variable, and then change the content based on that variable.
var newTab = window.open();
newTab.document.getElementById("id").value = username;
See https://stackoverflow.com/a/40031206/14006497.
CodePudding user response:
It would help if you provide some code to see how you are opening the tab.
If you do it with window.open
, you can focus like this:
var newTab = window.open("https://example.com", "_blank");
newTab.focus();
CodePudding user response:
Sorry, here is the code of the page with the buttons:
<button type="button" onclick="opencem()">CEM</button>
<button type="button" onclick="vascologin()">VASCO</button>
<script src="login.js">
</script>
And this is the js code with your suggestions:
function opencem() {
var newTab = window.open('https://slkub...');
newTab.focus();
newTab.document.getElementById('f-username').value = 'test';
}
But still i get the error:
Uncaught TypeError: Cannot set properties of null (setting 'value')
at opencem (login.js:235)
at HTMLButtonElement.onclick (login.html:29)