I'm trying to implement a simple Tampermonkey userscript in my Firefox browser that searches a current window (containing lines of debug logs) for a URL, then opens this URL using window.open(url, '_blank');
in a new tab.
This works perfectly fine. However, the next part is what I'm finding a bit hard; I'd like to have the new window open to a specific coordinates where a certain string exists, similar to opening a URL and then pressing Crtl + F and typign the string in the search bar. I know window.find(str);
works but when I use it, it searches for the str
in my current tab not the newly opened tab.
This is possible using text fragments (disclosure: I wrote this blog).
Text fragments allow linking directly to a specific portion of text in a web document, without requiring the destination webpage author to annotate it with an ID. They have been around for some time and are surprisingly powerful.
Say you are looking for the string apple, just do:
window.open(url + '#:~:text=apple' + , '_blank' ,'noopener');
The window will scroll to find the first instance of apple.
:~:
is fragment directive, and
text=
is text directive.
The link:
https://en.wikipedia.org/wiki/List_of_Apple_Inc._media_events#:~:text=macintosh
will take you the first "macintosh" instance.
Please note that "noopener" is required above as a security measure. This way the new page cannot manipulate the page which opened it. Read here
If you are looking to be more creative, please follow the docs here.