Chrome extension: run the contents of the Script before all embedded scripts are run on the page

I am trying to change some behavior of the YouTube player by changing some variables inside the player_api script embedded in the html video viewing page.

Nested script I'm trying to change

The problem is that I try, the built-in script player always works before my extension adds changes to it. Thus, maintaining player behavior is the same.

I tried setting the run_at property in my manifest to document-start , but then the script did not start at all.

What can I do to stop this script from executing until I enter it?

PS: I tried changing the script by intercepting the html call and editing the body using Charles Proxy , and the player behavior changed as I wanted. Therefore, he knows that this should work if it is done at the right time.

.

manifest.json

{
    "manifest_version": 2,
    "name": "YouFit For YouTube",
    "version": "1",
    "content_scripts": [{
        "js": ["content.js"],
        "matches": ["https://*.youtube.com/watch?*",
        "https://*.youtube.com/watch?*"],
    }],
    "browser_action": {
        "default_icon": "icon.png"
    }
}

content.js

function changeBehavior() {
    var scriptElements = document.getElementsByTagName('script');
    for (var i = 14; i < scriptElements.length; i++) {
        var curScriptBody = scriptElements[i].outerHTML;
        // Find the script i'm interested in
        if (curScriptBody.indexOf("var ytplayer") != -1) {
            scriptElements[i].outerHTML = scriptElements[i].outerHTML.replace("<text>", "<replacement text>");
            alert("Replaced");
            break;
        }
    }
}
changeBehavior();
+4
source share
1 answer

Have you tried something like this?

content.js

var script = document.createElement('script');
script.textContent = "/* What you have in content.js right now */";
(document.head||document.documentElement).prepend(script);
0
source

Source: https://habr.com/ru/post/1693655/


All Articles