{"id":17965362,"url":"https://github.com/t2ym/target-injector","last_synced_at":"2025-07-28T20:09:41.227Z","repository":{"id":146685333,"uuid":"305234977","full_name":"t2ym/target-injector","owner":"t2ym","description":"Wrapper to inject code into target","archived":false,"fork":false,"pushed_at":"2020-10-19T01:56:41.000Z","size":12,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-22T01:46:22.005Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/t2ym.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-19T01:46:13.000Z","updated_at":"2020-10-19T01:56:43.000Z","dependencies_parsed_at":"2023-04-01T13:18:24.833Z","dependency_job_id":null,"html_url":"https://github.com/t2ym/target-injector","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/t2ym/target-injector","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/t2ym%2Ftarget-injector","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/t2ym%2Ftarget-injector/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/t2ym%2Ftarget-injector/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/t2ym%2Ftarget-injector/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/t2ym","download_url":"https://codeload.github.com/t2ym/target-injector/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/t2ym%2Ftarget-injector/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267578003,"owners_count":24110351,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-28T02:00:09.689Z","response_time":68,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-29T12:41:54.536Z","updated_at":"2025-07-28T20:09:41.205Z","avatar_url":"https://github.com/t2ym.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![npm version](https://badge.fury.io/js/target-injector.svg)](https://badge.fury.io/js/target-injector)\n\n# target-injector\n\nHandy wrapper to inject code into targets\n\n```js\n// Insert a script element\nnew Injector('target.html');\n  .parse()\n  .select('html head') // cssauron syntax\n  .validate('prependChild') // valid iff the number of selected node is 1\n  .inject('\u003cscript src=\"injected-script.js\"\u003e\u003c/script\u003e')\n  .dest(injected =\u003e console.log(`${injected}`))\n  .dest('injected-target.html');\n\n// Modify a code fragment\nnew Injector('target.js' /* not read as data is specified */,\n    { data: 'function f() { const flag = true; }' }\n  )\n  .parse()\n  .select( // esquery syntax\n    '[type=\"FunctionDeclaration\"][id.name=\"f\"] ' +\n    '[type=\"VariableDeclaration\"][kind=\"const\"] ' +\n    '[type=\"VariableDeclarator\"][id.name=\"flag\"] ' +\n    '[type=\"Literal\"]'\n  )\n  .validate('replace')\n  .inject('false')\n  .dest(injected =\u003e console.log(`${injected}`));\n```\n\n# Install\n```sh\nnpm i target-injector\n# dependent components for handlers\nnpm i htmlparser2 domhandler cssauron espree estraverse esquery\n```\n\n# Set up `Injector` class\n```js\nconst { InjectorFactory, InjectionHandlerBase } = require('target-injector');\nconst { HtmlInjectionHandlerFactory } = require('target-injector/HtmlInjectionHandlerFactory.js');\nconst { JsInjectionHandlerFactory } = require('target-injector/JsInjectionHandlerFactory.js');\n\n// Notes: \n//  - target-injector NPM package does NOT explicitly depend on any other packages\n//  - These dependent components must be installed into the user project/package\nconst { Parser } = require(\"htmlparser2\");\nconst { DomHandler } = require(\"domhandler\");\nconst cssauron = require('cssauron');\nconst parser = require('espree'); // can be esprima or acorn\nconst estraverse = 'estraverse'; // hand the specifier to patch the component in InjectorFactory\nconst esquery = require('esquery');\n\nconst Injector = InjectorFactory({\n  html: {\n    factory: HtmlInjectionHandlerFactory,\n    components: {\n      Parser, DomHandler, cssauron,\n    },\n    extensions: [ '.html', '.htm' ],\n  },\n  js: {\n    factory: JsInjectionHandlerFactory,\n    components: {\n      parser, estraverse, esquery, /*, parserOptions: parserOptions */\n    },\n    extensions: [ '.js', '.mjs' ],\n  },\n});\n```\n\n# Examples\n\n## Injection with fallback\n```js\nnew Injector('target.html');\n  .parse()\n  .select('html head script[src=/injected-script.js/]', 'html head') // fallback selectors\n  // Suppored actions: 'replace', 'insertBefore', 'insertAfter', 'prependChild', 'appendChild'\n  .validate('replace', 'prependChild') // replace the script element if found\n  .inject(...[ 'replaced', 'prepended' ].map(attr =\u003e `\u003cscript ${attr} src=\"injected-script.js\"\u003e\u003c/script\u003e`))\n  .dest(injected =\u003e console.log(`${injected}`))\n  .dest('injected-target.html');\n```\n\n## Patch JavaScript code with chaining\n```js\n// JavaScript: Extracted from target-injector/Injector.js\n// Patch estraverse.attachComments for trailingComments to work\nlet estraverse = 'estraverse';\nnew Injector(require.resolve(estraverse))\n  .parse().select(\n    '[type=\"FunctionDeclaration\"][id.name=\"attachComments\"] ' +\n    '[type=\"ObjectExpression\"] ' +\n    '[type=\"Property\"][key.name=\"leave\"] ' +\n    '[type=\"BinaryExpression\"][operator=\"\u003c\"] ' +\n    '[type=\"MemberExpression\"][object.property.name=\"extendedRange\"]'\n  ).validate('insertAfter').inject(' - 1')\n  .parse().select(\n    '[type=\"FunctionDeclaration\"][id.name=\"attachComments\"] ' +\n    '[type=\"ObjectExpression\"] ' +\n    '[type=\"Property\"][key.name=\"leave\"] ' +\n    '[type=\"BinaryExpression\"][operator=\"===\"] ' +\n    '[type=\"MemberExpression\"][object.property.name=\"extendedRange\"]'\n  ).validate('insertAfter').inject(' - 1')\n  .parse().select(\n    '[type=\"FunctionDeclaration\"][id.name=\"attachComments\"] ' +\n    '[type=\"ObjectExpression\"] ' +\n    '[type=\"Property\"][key.name=\"leave\"] ' +\n    '[type=\"BinaryExpression\"][operator=\"\u003e\"] ' +\n    '[type=\"MemberExpression\"][object.property.name=\"extendedRange\"]'\n  ).validate('insertAfter').inject(' - 1')\n  .dest(injected =\u003e {\n    estraverse = {};\n    let _module = { exports: estraverse };\n    new Function('module', 'exports', 'require', injected)(_module, estraverse, require);\n    Injector.handlers.js = handlers.js.factory(Object.assign(handlers.js.components, { estraverse }));\n  });\n```\n\n## Validator and Injection Strings as a callback function\n```js\n// \nlet injector = new Injector('target.html');\ninjector\n  .parse()\n  .select('html head meta[charset]', 'html head')\n  .validate(function (injector) {\n    // this === injector\n    if (this.selected \u0026\u0026 this.selected.length === 1) {\n      switch (this.selector) {\n      case 'html head':\n        injector.action = Injector.PREPEND_CHILD;\n        break;\n      case 'html head meta[charset]':\n        injector.action = Injector.INSERT_AFTER;\n        break;\n      default:\n        injector.action = Injector.INSERT_AFTER;\n        break;\n      }\n      return true;\n    }\n    else {\n      this.error = `only 1 node must be selected ${this.selected}`;\n      return false;\n    }\n  })\n  .inject(function (injector) {\n    switch (this.selector) {\n    case 'html head':\n      attr = 'first-head-child';\n      break;\n    case 'html head meta[charset]':\n      attr = 'after-meta-charset';\n      break;\n    default:\n      attr = 'unknown';\n      break;\n    }\n    return `\u003cscript ${attr} \"injected-script.js\"\u003e\u003c/script\u003e`;\n  }\n  .dest('injected-target.html')\n```\n\n## JavaScript injection with next and prev attributes\n```js\nnew Injector('target.js' /* not read as data is specified */, \n    { data: `const arr = ['a', 'b', 'c', 'd', 'e']` }\n  )\n  .parse()\n  .select( // esquery syntax with next and prev attributes\n    '[type=\"VariableDeclaration\"][kind=\"const\"] ' +\n    '[type=\"VariableDeclarator\"][id.name=\"arr\"] ' +\n    '[type=\"Literal\"][prev.value=\"b\"]'\n  )\n  .validate('insertAfter')\n  .inject(`, 'inserted after c'`)\n  .parse()\n  .select( // esquery syntax with next and prev attributes\n    '[type=\"VariableDeclaration\"][kind=\"const\"] ' +\n    '[type=\"VariableDeclarator\"][id.name=\"arr\"] ' +\n    '[type=\"Literal\"][next.value=null]'\n  )\n  .validate('replace')\n  .inject(`'replaced last element value'`)\n  .dest(injected =\u003e {\n    // injected === \n    // `const arr = ['a', 'b', 'c', 'inserted after c', 'd', 'replaced last element value']`\n    console.log(`${injected}`);\n  })\n```\n\n## Select a node with `trailingComments`\n```js\nnew Injector('target.js' /* not read as data is specified */, { data: `\n  obj.prop = {\n    item1: true, // comment for item1\n    item2: true, // comment for item2\n  };\n` })\n  .parse()\n  .select( // leadingComments and trailingComments are supported\n    '[type=\"AssignmentExpression\"][left.object.name=\"obj\"][left.property.name=\"prop\"] ' +\n    '[type=\"ObjectExpression\"] ' +\n    '[type=\"Property\"][value.trailingComments.0.value=/comment for item2/] '\n  )\n  .validate('replace').inject('item2: \"new item2 value\"')\n  .dest(injected =\u003e { console.log(`${injected}`); })\n```\n\n# License\n\n[BSD-2-Clause](https://github.com/t2ym/thin-hook/blob/master/plugins/target-injector/LICENSE.md)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ft2ym%2Ftarget-injector","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ft2ym%2Ftarget-injector","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ft2ym%2Ftarget-injector/lists"}