Is there a way to force the focus on a determined window tab?

A little bit of background: I’m working with ServiceNow and we’re trying to build a custom UI Page/Portal Widget that can listen to an external barcode scanner, this solution is mobile-focused. The plan is to use a Mobile Web Screen so we can call this page from the ServiceNow Agent App. (OOTB Barcode Scanner via mobile does not meet our business needs).

The challenge I’m facing right now is that I have a simple HTML page with an input, and then I added a load event to focus the input after the page loads.

This works well if we try the page from desktop, but once we try it from the mobile app, it doesn’t work.

Desktop View vs
Mobile View

I have tried a bunch of different things:

  • $j( '#input_asset_tag' ).focus();
  • window.focus()
  • document.activeelement.blur()
  • $j( '#input_asset_tag' ).click();

I realized that the mobile window does not have a focus when it is opened by adding this line of code to the load event:
alert( 'Has focus: '+ document.hasFocus() );

So now when the page is opened I get an alert that tells me if the document has focus.
In desktop returns true, but mobile returns false:
Desktop has focus vs Mobile has no focus

The main issue is that the mobile web window is not focused by default. I tried setting a timeout and after 5 seconds ran this line: $j( '#input_asset_tag' ).focus();, Then opened the mobile web screen, tab on any part of the screen before the 5 seconds were reached and then that worked, the input got focused.

Also, I tried adding another event “keypress” so we can listen to the external barcode scanner this way, but it doesn’t seem to work until you set the focus on the window (tab on any part of the screen).

We need this solution to work without the user having to click on the screen, the only responsibility of the user should be to press the scan button on the hardware to scan barcodes and leave the rest to the app.

*$j(‘element’) is the syntax used in ServiceNow to call jQuery.

*This is how the load event looks like:

window.addEventListener( 'load', function(){
    $j( '#input_asset_tag' ).focus();
    alert( 'Has focus: '+ document.hasFocus() );

});

I found an article stating this depends entirely on the browser and we don’t have too much control over this, but I’m still not convinced.