How to implement a flexible system for dynamically injecting scripts and styles into pages using the scripting API?
The transition to new security standards in extensions has led to abandoning the old method of executing arbitrary code via text strings in favor of a safer dynamic injection API. The modern API allows programmatically attaching pre-prepared script files and stylesheets to specific tabs when desired events occur. This approach eliminates vulnerabilities associated with dynamic code execution and gives the developer complete control over exactly what content and at what time enters the isolated space of a web page.
When designing injection functionality, it is important to consider the execution context limitations. Scripts can run either in the extension's isolated world, where there is access to special browser APIs but no access to page variables, or in the page's main world, where code works with the site's actual context. Choosing the correct context depends on the task at hand: interacting with the page's DOM tree often requires the main world, whereas sending network requests via the extension infrastructure is better suited for the isolated environment.
To correctly organize dynamic code injection, it is recommended to follow this algorithm:
Skillful application of these tools allows creating powerful tools for modifying web pages on the fly without violating browser security policies.