简体   繁体   中英

Chrome Extension content_script at both document_start and document_end

Good day to everyone, as you can see I'm pretty new at Chrome extensions.

Can you run a script from content_scripts before and after the the DOM or page fully loads?

Like:

"content_scripts": [ {
    "matches": ["<all_url>"],
    "js": ["content.js"],
    "all_frames": true,
    "run_at": "document_start",
    "run_at": "document_end"
} ]

Or something like:

 "content_scripts": [ {
    "matches": ["<all_url>"],
    "js": ["content1.js"],
    "all_frames": true,
    "run_at": "document_start"
} ],
"content_scripts": [ {
    "matches": ["<all_url>"],
    "js": ["content2.js"],
    "all_frames": true,
    "run_at": "document_end"
} ]

You can have only one content_scripts entry, so it would be like:

"content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content1.js"],
    "all_frames": true,
    "run_at": "document_start"
  },{
    "matches": ["<all_urls>"],
    "js": ["content2.js"],
    "all_frames": true,
    "run_at": "document_end"
}]

With this setting, content1.js would run at the beginning and content2.js at the end.

You are going in the right direction: You can use the run_at property, but your manifest needs to look something like this:

"content_scripts": [
{
    "matches": ["<all_url>"],
    "js": ["content1.js"],
    "all_frames": true,
    "run_at": "document_start"
},
{
    "matches": ["<all_url>"],
    "js": ["content2.js"],
    "all_frames": true,
    "run_at": "document_end"
}]

It should be an array of objects defining all content scripts instead to declaring the content_script property twice.


If you are using jQuery you can also use $(document).ready() like this:

 const func1 = params => { // Stuff that will happen as soon as it can }; $(document).ready(() => { // stuff that will happen when DOM is ready });

If you are not using jQuery you can just do a quick google search to find alternatives for $(document).ready in vanilla js.


Other solution you can use it to inject content script programmatically from background script using chrome.tabs.executeScript() docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM