kisai
kisai

Reputation: 313

How to detect if an unwanted chrome content-script has being injected in my page?

This is a security question, I want to avoid the injection of code via chrome content-scripts, how to detect if that is the case?

assumptions:

content-script is malicious code, so it will probably avoid message passing responses.

Upvotes: 4

Views: 3232

Answers (3)

BigJ
BigJ

Reputation: 2032

Content scripts have access to the same DOM but run in a isolated environment, which means they can't access/alter your javascript, but they can alter your DOM.

If you want to detect a content script altering your DOM, you could listen for DOM changes with MutationObserver. If you don't alter the DOM yourself (with React for example) you could listen to any change.

Upvotes: 1

Scott Finlay
Scott Finlay

Reputation: 86

You could try adding such a script to your own browser and see how it appears. If it does appear in the rendered HTML, then maybe it's possible to detect it with JavaScript:

$('script').filter(function () {
    var src = $(this).attr('src'),
        result,
        externalScripts = [];
    if(src !== undefined){
        //check for scripts which are not served from your domain
        //you could also try just returning the scripts which have no src attribute
        result = src.match(/^(?:https?:)\/\/expected.domain.com/);
        if(result === null) {
            externalScripts.push(src);
        }
    }

    return externalScripts;
})

But most likely it's not possible to detect as it sounds like Chrome scripts are sandboxed. The best way to find out how to prevent a thing is to try doing that thing yourself and see how it affects the page.

You should also ask yourself if it's really necessary to prevent this. It seems unlikely that this is a security risk.

Upvotes: 0

Haibara Ai
Haibara Ai

Reputation: 10897

To my knowledge, it's not possible.

According to Execution environment,

  1. Content scripts execute in a special environment called an isolated world

  2. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page.

  3. JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

I believe #3 has told us that if the extension is not under our control, we have no idea whether there are some content scripts are running.

Upvotes: 4

Related Questions