Search code examples
javascriptangulartypescriptgoogle-chrome-extension

Modify Angular menu-bar from Chrome Extension content-script


I have been working on an extension (google chrome only for now) that is supposed to add features to my school's online learning environment. This website (not actually run by the school itself) uses Angular for the front-end.

For the extension I am using Typescript, with Parcel. The scripts that are running on the webpages are content-scripts.

I am trying to add an item to the menu-bar that is on the left. This is what I've tried:

  • Inserting pure HTML into the ul element, but this breaks the entire menu-bar and the user is unable to use it after.

  • Use Angular (installed via NPM) in the content-script to find the scope of the menu-bar element, then add the new option (Menu-bar is an array) and then apply it. Although this also seems to not work, like so:

    Expected behaviour (using browser console)

    let target = document.getElementsByClassName("main-menu")[0];
    let menu = angular.element(target);
    console.log(menu);
    >>> p.fn.init [ul.main-menu, context: ul.main-menu]
    

    Received Behaviour (from content-script)

    let target = document.getElementsByClassName("main-menu")[0];
    let menu = angular.element(target);
    console.log(menu);
    >>> p.fn.init [ul.main-menu]
    

    The absence of the context makes me think that my content-script and the webpage's script are not running in the same scope. Is that correct? I am not able to use the .scope() method in the content-script either.

This is my manifest.json for the plugin. Please let me know

{
    "name": "Magister Plus",
    "description": "TBD",
    "version": "0.0.1",
    "manifest_version": 3,
    "permissions": [
        "activeTab",
        "scripting",
        "tabs"
    ],
    "background": {
        "service_worker": "./background/background.js"
    },
    "host_permissions": [
        "https://*.magister.net/*"
    ],
    "content_scripts": [
        {
            "matches": ["https://*.magister.net/*"],
            "js": ["./content/domain.js"]
        },
        {
            "matches": ["https://*.magister.net/magister/#/vandaag"],
            "js": ["./content/vandaag.js"]
        }
    ],
    "action": {}
}

I am not really sure what to do here anymore, since I am not really familiar with Angular.js at all.

Thanks for any help!


Solution

    1. To change html you need to use appendChild or insertAdjacentHTML, but not innerHTML. 2) To access context property you need to run that part of code in page context. By @wOxxOm

    This worked indeed! Thank you so much!