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
- Create two new
js
Documentation.cap (a poem)
- exist
content_scripts
embedded indocuments and
file
- exist
hit the nail on the head
Dispatch Customization
custom event
messages - exist
hit the nail on the head
addEventListener
listen to messages - exist
hit the nail on the head
addEventListener
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 certainty
DOM
which is the same as the hosting page's home domain, theJavaScript
Shared execution environment
- indicate clearly and with certainty
1.2 Programmatic processes
The flowchart is shown below:
2. Access to content
gain
window
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
4. Dynamic access to data
4.1. Click on the button
4.2 Data return
5. Code address
- Gitee
- Github
IV. Summary
1. Summary of articles
- Getting the current page's window object is different from the document object, so it needs to be handled in a different way.
- This time, three solutions are provided, the core principle is embedded in the current page, through the message dispatch and receive to get data
- The first is more familiar via postMessage, and customizing the Event is a bit more complicated.
- 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】