target-injector
Handy wrapper to inject code into targets
// Insert a script element'target.html'; // cssauron syntax // valid iff the number of selected node is 1 ; // Modify a code fragment'target.js' /* not read as data is specified */ data: 'function f() { const flag = true; }' ;
Install
npm i target-injector# dependent components for handlers npm i htmlparser2 domhandler cssauron espree estraverse esquery
Injector
class
Set up const InjectorFactory InjectionHandlerBase = ;const HtmlInjectionHandlerFactory = ;const JsInjectionHandlerFactory = ; // Notes: // - target-injector NPM package does NOT explicitly depend on any other packages// - These dependent components must be installed into the user project/packageconst Parser = ;const DomHandler = ;const cssauron = ;const parser = ; // can be esprima or acornconst estraverse = 'estraverse'; // hand the specifier to patch the component in InjectorFactoryconst esquery = ; const Injector = ;
Examples
Injection with fallback
'target.html'; // fallback selectors // Suppored actions: 'replace', 'insertBefore', 'insertAfter', 'prependChild', 'appendChild' // replace the script element if found ;
Patch JavaScript code with chaining
// JavaScript: Extracted from target-injector/Injector.js// Patch estraverse.attachComments for trailingComments to worklet estraverse = 'estraverse';require ;
Validator and Injection Strings as a callback function
// let injector = 'target.html';injector
JavaScript injection with next and prev attributes
'target.js' /* not read as data is specified */ data: `const arr = ['a', 'b', 'c', 'd', 'e']`
trailingComments
Select a node with 'target.js' /* not read as data is specified */ data: ` obj.prop = { item1: true, // comment for item1 item2: true, // comment for item2 };`