Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: Run Content Script before any Embedded Scripts run on Page

I'm trying to change some behavior of the YouTube player, by changing some variables inside of the player_api script that is embedded into the html watch page of videos.

The embedded script i'm trying to modify

Problem is, whatever i try, the embedded script of the player always runs before my extension adds modifications to it. Thus keeping the behavior of the player the same.

I tried setting the run_at property in my manifest to document-start, but then the script didn't run at all.

What can i do to halt the execution of that script until i make changes to it?

PS: I tried changing the script by intercepting the html call and editing the body with Charles Proxy and the behavior of the player changed as i wanted. So it know it should work, if 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();
like image 620
DarkMental Avatar asked Feb 14 '18 19:02

DarkMental


1 Answers

Did you try 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);
like image 194
Chris Cinelli Avatar answered Oct 05 '22 00:10

Chris Cinelli