Proxy Interception Case

Background:

Simply put, you override the call logic by intercepting function calls without modifying page calls.

Each burial point of the GA page of the applet is already buried, but a new GA account needs to be added

And while GA can create multiple instances, one instance needs to be called once by default

For example, a buried page track1.send() is an object

Now you can’t call two instances per page, or else

track1.send()

track2.send()

If there is a third one, each page needs to be followed by track3.send(), at least dozens of pages, which is not feasible

So what we want to do is return track1, return an array, intercept it by proxy,

Methods are called externally once and internally for each array element

The following is a proxy interception implementation example

/ / change the former
const obj = {
    send(val) {
      console.log(val + '1')}},// page call
obj.send('Sent')

/ / changed
const arr = [
  {
    send(val) {
      console.log(val + '1')}}, {send(val) {
      console.log(val + '2')}},]const obj = new Proxy(arr, {
  get: function (target, key) {
    return function () {
      arr.forEach((v) = >{ v[key](... arguments) }) } }, })// page call
obj.send('Sent')

Copy the code

You’ll notice that the code that the page calls hasn’t changed, it’s done what we wanted to do,