简体   繁体   中英

Chrome Extensions: Use a content script to modify existing scripts on a web page?

I'm creating a chrome extension that needs to hook into another script that already exists on my target web page. For simplicity's sake, I'm trying to find the following existing script element on a page and add a console.log() to it.

<script type="text/javascript">
    var viewModel = new ScenePlayViewModel('', 'Ace', false);
    viewModel
        .load('jgWJJ2qsxx')
        .then(function () {
            sceneDOM = new SceneEditDOM2(viewModel.scene());
            sceneDOM.init();
            viewModel.isSubmitViaShareUrl(false);
            viewModel.isSubmitViaUnityPackage(false);
            console.log("HOOK INJECTED"); <--------------------------------------------- line to add
        });

</script>

I've tried a number of solutions but none of them have seemed to work. For example, I've tried using a content script to find the script and replace the text, but it appears to run the pre-change script instead of my modified code.

// replaces javascript on website, but doesn't run new version

var scriptLoadScene = $("script:contains('new ScenePlayViewModel')"); // find the script
scriptLoadScene.text("console.log('Hello World')"); // change the text

What should I do? Basically, I'm just trying to change/add scripts to the web page to add more features.

This doesn't exactly answer your question, but hopefully will help you find a solution.

First - hopefully someone with more knowledge than me will confirm or discredit this - from my understanding, the script code is only run once, on page load, unless otherwise triggered by some event. Since Chrome extensions are triggered after the page has loaded, this script will have already been run, and anything inserted after won't run unless triggered.

I suppose you could always call the function again after you've edited it, but I don't have the knowledge or experience to predict what would happen then.

In my experience, I've just added my own '' tags with the code I wanted to run by writing them into the DOM, either into the '' or '' element.

Best of luck. -brent

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