MCPcopy Create free account
hub / github.com/Useful-Scripts-Extension/useful-script / hook

Method hook

scripts/libs/js-hook/index.js:342–399  ·  view source on GitHub ↗

* hook core function * @param parentObj {Object} - required The parent object that the hook function depends on * @param hookMethods {Object|Array|RegExp|string} - required The function name of the hooked function or the matching rule of the function name * @param fn {Function} -required

(parentObj, hookMethods, fn, type, classHook, context, proxyHandler)

Source from the content-addressed store, hash-verified

340 * @returns {boolean}
341 */
342 hook (parentObj, hookMethods, fn, type, classHook, context, proxyHandler) {
343 /* Support parameter passing in object form */
344 const opts = arguments[0]
345 if (util.isObj(opts) && opts.parentObj && opts.hookMethods) {
346 parentObj = opts.parentObj
347 hookMethods = opts.hookMethods
348 fn = opts.fn
349 type = opts.type
350 classHook = opts.classHook
351 context = opts.context
352 proxyHandler = opts.proxyHandler
353 }
354
355 classHook = toBoolean(classHook)
356 type = type || 'before'
357
358 if ((!util.isRef(parentObj) && !util.isFn(parentObj)) || !util.isFn(fn) || !hookMethods) {
359 return false
360 }
361
362 const t = this
363
364 hookMethods = t._getObjKeysByRule(parentObj, hookMethods)
365 hookMethods.forEach(methodName => {
366 if (!t.isAllowHook(parentObj, methodName)) {
367 util.debug.log(`${util.toStr(parentObj)} [${methodName}] does not support modification`)
368 return false
369 }
370
371 const descriptor = Object.getOwnPropertyDescriptor(parentObj, methodName)
372 if (descriptor && descriptor.writable === false) {
373 Object.defineProperty(parentObj, methodName, { writable: true })
374 }
375
376 const originMethod = parentObj[methodName]
377 let hookMethod = null
378
379 /* Non-functions cannot be hooked */
380 if (!util.isFn(originMethod)) {
381 return false
382 }
383
384 hookMethod = t._proxyMethodcGenerator(parentObj, methodName, originMethod, classHook, context, proxyHandler)
385
386 const hookMethodProperties = hookMethod[t.hookPropertiesKeyName]
387 if (hookMethodProperties.classHook !== classHook) {
388 util.debug.log(`${util.toStr(parentObj)} [${methodName}] Cannot support functions hook and classes hook at the same time `)
389 return false
390 }
391
392 /* Use hookMethod to take over the method that needs to be hooked */
393 if (parentObj[methodName] !== hookMethod) {
394 parentObj[methodName] = hookMethod
395 }
396
397 t._addHook(hookMethod, fn, type, classHook)
398 })
399 }

Callers 6

hookClassMethod · 0.95
beforeMethod · 0.95
afterMethod · 0.95
replaceMethod · 0.95
errorMethod · 0.95
hangUpMethod · 0.95

Calls 4

_getObjKeysByRuleMethod · 0.80
isAllowHookMethod · 0.80
_addHookMethod · 0.80

Tested by

no test coverage detected