Location>code7788 >text

Chrome plugin to get the web page window object (Program 3)

Popularity:318 ℃/2024-09-05 10:11:58

preamble

Recently there was a need to get a browser plugin towindow object under some data, which seemed simple enough at the time, and thedocument Likewise, directly by embedding thecontent_scripts Get it directly and then use thesendMessage Just send the data to the plugin and it turns out that's not the case...

Not recommended for use here Performing an injection will likely report an error:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost😗 http://127.0.0.1😗". Either the 'unsafe-inline' keyword, a hash ('sha256-P5exJBBLYN1KVh+CK9MkXvRal4ZQQu9VaKPvx4JuVLE='), or a nonce ('nonce-...') is required to enable inline execution.

Chrome plugin to get web page window object (Option 1)

Chrome plugin to get the web page window object (scheme two)

One or two files, passing messages through CustomEvent

1. Programmatic thinking

  1. Create two newjs Documentation. cap (a poem)
  2. existcontent_scripts embedded in documents and file
  3. exist hit the nail on the head Dispatch Customizationcustom event messages
  4. exist hit the nail on the headaddEventListener listen to messages
  5. exist hit the nail on the headaddEventListener listens for messages and then passes them through thedispatchEvent send a message

1.1. content_scripts Embedding JS Files

Be sure to put The file is placed in the In front of the document

content_scripts Add You need to add the"world": "MAIN" field

world is an enumeration type (math.)

  • ISOLATED default value
    • Execution environment unique to this extension
  • MAIN
    • indicate clearly and with certaintyDOM which is the same as the hosting page's home domain, theJavaScript Shared execution environment

1.2 Programmatic processes

The flowchart is shown below:

image

2. Access to content

gainwindow lowerMyBlog field

 = {
  juejin: '/user/2409752520033768/posts',
  csdn: '/',
  'chrome-blog': {
    netlify: '/',
    github: '/extension/'
  }
}

3. Code implementation

3.1.

/**
 * index The file sends a message to the file
 * @param {string} type custom typology
 * @param {any} data digital
 */
const indexSendMessageToLucky = async (type, data) => {
  (new CustomEvent('custom-index-type', { detail: { type, data } }))
  return new Promise((res) => {
    function handleResponse(e) {
      const detail =
      if ( == type) {
        ('custom-lucky-type', handleResponse)
        return res()
      }
    }
    ('custom-lucky-type', handleResponse)
  })
}

/**
 * send a message
 */
const sendMessage = () => {
  function getMyBolg() {
    return
  }
  indexSendMessageToLucky('run-index-fun', {
    function: ()
  }).then((res) => {
    ('res-->', res)
  }).catch((e) => {
    ('e', e)
  })
}
/**
 * initialization
 */
const init = () => {

  // stick button buttons
  const button = ('button')
   = '获取digital'
   = 'chrome-ext-but'
  (button)
   = () => {
    sendMessage()
  }
  // initialization获取digital
  sendMessage()
}

// judgements cap (a poem) self Are they equal?,If not equal,then it is not injected
if ( == ) {
  init()
}

3.2.

/**
 * event listener
 */
('custom-index-type', async (e) => {
  const { type, data } =
  switch (type) {
    case 'run-index-fun': {
      const fn = new Function(`return (${})(...arguments)`)
      const rs = await fn(...( ?? []))
      luckySendMessageToIndex(type, rs)
      break
    }
  }
})

/**
 * lucky The file sends a message to the file
 * @param {string} type custom typology
 * @param {any} data digital
 */
const luckySendMessageToIndex = (type, data) => {
  (
    new CustomEvent('custom-lucky-type', {
      detail: { type, data, file: 'lucky' }
    })
  )
}

3.3.

{
  "manifest_version": 3,
  "name": "Get Winddow Object Field",
  "version": "1.0",
  "description": "Gets the field under window",
  "content_scripts": [
    {
      "js": [
        ""
      ],
      "matches": ["http://localhost:*/*"],
      "run_at": "document_end",
      "world": "MAIN"
    },
    {
      "js": [
        ""
      ],
      "matches": ["http://localhost:*/*"],
      "all_frames": true,
      "run_at": "document_end"
    }
  ],
  "background": {
    "service_worker": ""
  },
  "host_permissions": [
    "http://localhost:*/*"
  ],
  "permissions": [
  ],
  "web_accessible_resources": []
}

3.4 Structure of the project document

.
├── 
├── 
├── 
├── 
└── 

3.5 Programmatic impact

Select the current plugin in the console to see the acquiredwindow lowerMyBlog boyfriend

image

4. Dynamic access to data

4.1. Click on the button

image

4.2 Data return

image

5. Code address

  • Gitee
  • Github

IV. Summary

1. Summary of articles

  1. Getting the current page's window object is different from the document object, so it needs to be handled in a different way.
  2. This time, three solutions are provided, the core principle is embedded in the current page, through the message dispatch and receive to get data
  3. The first is more familiar via postMessage, and customizing the Event is a bit more complicated.
  4. I've uploaded the code for all three scenarios to gitee/github

2. Code address

  • Gitee:/gqk-chrome-extension/get-window-fields
  • Github:/gqk-chrome-extension/get-window-fields/tree/main

quote

  • chrome extensions mv3 injects/gets window data from original site via content scripts
  • CustomEvent: CustomEvent() Constructor
  • Content_script world