Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

javascript - Chrome extension set to `run_at` `document_start` is running too fast?

EDIT: Something was wrong with my Chrome browser and creating a conflict with my script, a full reinstall eliminated whatever the problem source was. If I happen to find out what was causing it I will include it in here.

EDIT2: Just to let anyone reading this in 2017 know that I haven't forgotten this and I have never had this problem since my previous edit.

EDIT3: It is 2019 and so far I've never had this problem again.


I have been learning how to create a simple Chrome extension which is a userscript port. The script works perfectly with Tampermonkey with the setting run at to document-start, all the necessary events that need to be caught from the beginning are all captured.

However, when I set the same settings in the Chrome extension I discovered that the same running setting is faster than Tampermonkey's which causes the first function to fail: (Uncaught TypeError: Cannot call method 'appendChild' of null.) since it tries to append a script element to the head section, which doesn't exist until 0.010s later.

My dirty solution so far has been to make use of a setInterval function with the timer set to 10 to check if document.head exists and then proceed with the code if the condition is true.

Is there any way that I can make this work correctly without having to resort to setInterval or maybe replicate Tampermonkey's grant none option which appears to run the userscript on the webpage context?

The following is my manifest.json file:

{
    "manifest_version": 2,
    "content_scripts": [ {
        "js":        [ "simpleuserscript.user.js" ],
        "matches":   [ "https://www.google.com/*"],
        "run_at":    "document_start"
    } ],
    "converted_from_user_script": true,
    "description":  "Chrome extension",
    "name":         "Testing",
    "version":      "1"
}

All of this could be avoided if Chrome would adopt the afterscriptexecute event, but until that happens I am stuck with the load event. I thank in advance any help provided.


EDIT: I have already tried the suggestions in the replies: using a different run at point, using DOMContentLoaded and append to document.documentElement. All were unsuccessful because: 1 and 2 makes the script miss early events, and 3 returns the same TypeError as when trying to append to document.head.

The script has to be inserted/running when document.readyState = loading or else it will miss early necessary events, but not so early to the point of being unable to append childs to either documentElementor head

An example of the code inside simpleuserscript.user.js:

var script = document.createElement("script");
script.textContent = "console.log('success')";
if(document.head) {
    document.head.appendChild(script);
} else if(document.documentElement) {
    document.documentElement.appendChild(script);
}

Console will show TypeError: Cannot call method 'appendChild' of null

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Chrome extension Content scripts (run from a manifest.json) that are run at document_start, do fire before document.readyStateDoc has reached interactive -- which is the earliest you want to start messing with most page elements.

However, you can inject most <script> nodes right away if you wish. Just not to document.head or document.body because they don't exist yet.
Append to documentElement instead. For example:

var s = document.createElement ("script");
s.src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js";
s.async = false;
document.documentElement.appendChild (s);

Or

var s = document.createElement ("script");
s.src = chrome.extension.getURL ("MyPwnCode.js");
s.async = false;
document.documentElement.appendChild (s);

If you are adding or modifying other DOM elements, in a script running at document_start, wait until the DOMContentLoaded event like so:

document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false);

function fireContentLoadedEvent () {
    console.log ("DOMContentLoaded");
    // PUT YOUR CODE HERE.
    //document.body.textContent = "Changed this!";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...