javascript – How to run a script on a page without having to open it in a browser tab or window?

Question:

I need to make a web-extension (add-on) that can handle DOM elements, existing events and run scripts in the context of a website page.

But do I need this to happen in the background without the page being explicitly in the user's browser, that is, I want to manipulate a page without having to open it in a tab or window?

Answer:

One of the ways to do this is using iframe , below is an example of how to do it (examples using jquery).

Create the iframe and style it accordingly to make it invisible to the user:

let iframe = "<iframe id='iframe' src='https://pt.stackoverflow.com' style='display:none;visibility:hidden' />";
$("body").append(iframe);

To handle elements inside the iframe, use .contents :

let page = $("#iframe").contents();

Now just look for the elements:

page.find("input");
Scroll to Top