Enhancing Browser Experience: The correct method for dynamically adding an AngularJS controller through a Chrome Extension's Content

Currently, I am in the process of developing a Chrome extension using AngularJS.

To attach a controller to the required DOM elements on a webpage, I have been utilizing the following content script code:

setController() {
    if(this.setContollerCondition) {
        this.controllerElement.attr('ng-controller', 'Controller as cntrl');
    }
}

However, I have encountered an issue where this method is not consistently effective, as the controller constructor fails to initiate and the 'ng-scope' does not get applied to the element.

My query is regarding the appropriate approach to dynamically attach a controller. If my current method is accurate, could you help point out where I might be making mistakes?

Here is an overview of the sequence of activities occurring in the Chrome extension upon page load:

  1. If ng-app is not initialized, it is then initialized.
  2. Initialization of functions functioning as event listeners
  3. Checking the host URL and executing the suitable initialization function based on the URL
    • If a specific DOM element is added, customised DOM elements of the extension are included, followed by utilizing the setController() function to add the Controller to the element.

Most of these functions involve asynchronous calls.

Current observed behavior includes:

  1. The controller is effectively implemented and operates seamlessly with a particular host like web.whatsapp.com
    • All extension buttons are correctly positioned and perform exceptionally well within this host environment.
  2. In another scenario with a different host, such as www.linkedin.com, the controller is sporadically set and at times not set.
    • Occasionally, the button is placed but when it is not, the ng-scope attribute is not applied to the DOM element due to the failure of initializing the controller constructor.
  3. For a third host, in this case mail.google.com, the controller is never set.
    • While the button is always included, the scope is not applied to the necessary DOM element and the Controller constructor remains uninvoked.

The project incorporates Webpack and ES6 for its development requirements.

Provided below are some files resembling the actual code structure to facilitate a better understanding of the problem:

manifest.json

{
"manifest_version": 2,

"name": "MyExtension",
"short_name": "MyExtension",
"omnibox": {
    "keyword": "MyExtension"
},
"description": "Description",
"version": "2.0.7",
"version_name": "2.0.7",
"browser_action": {
    "default_icon": {
        "128": "assets/images/icon-v2-128px.png",
        "16": "assets/images/icon-v2-16px.png",
        "48": "assets/images/icon-v2-48px.png"
    },
    "default_title": "MyExtension",
    "default_popup": "index.html"
},
"content_scripts": [ {
    "js": [ "assets/lib/angular.min.js", "assets/lib/jquery-2.2.3.min.js", "assets/lib/bootstrap.min.js", "dist/contentScript.bundle.js" ],
    "css": ["assets/css/font-awesome.min.css", "assets/css/bootstrapInject.css", "assets/css/injectingStyle.css"],
    "matches": ["*://*.linkedin.com/*", "*://web.whatsapp.com/*", "*://mail.google.com/*"],
    "run_at": "document_end"
} ],
"background": {
    "page": "background.html"
},
"permissions": [
    "tabs",
    "http://*/*",
    "https://*/*",
    "contextMenus",
    "notifications",
    "unlimitedStorage",
    "storage"
],
"icons": {
    "128": "assets/images/icon-v2-128px.png",
    "16": "assets/images/icon-v2-16px.png",
    "48": "assets/images/icon-v2-48px.png",
    "16": "assets/images/icon-v2-16px.png"
},
"web_accessible_resources": [
    "all required files here"
],
"update_url": "https://clients2.google.com/service/update2/crx",
"content_security_policy": "script-src 'self' 'unsafe-eval' https://ssl.google-analytics.com https://connect.facebook.net https://platform.twitter.com https://staticxx.facebook.com; object-src 'self'"
}

init.js file responsible for attaching the controller:

export default class AddContactModule {
constructor() {
   // Code logic goes here...
}

// More functions and operations are defined within this class for handling events and adding contact models.

A snippet from the controller.js file:

"use strict";
import AddContactModule from './init'

export default class ContactModalController {
constructor($scope, $compile) {
    // Initialization and declaration of essential objects required for smooth operation.
}

// Additional methods and functionalities like fetching details from LinkedIn are showcased here.

Answer №1

I encountered a problem like this before where the controller wasn't being initialized.

I positioned the app in the HTML element and the controller in the body element.

In my opinion, the problem stems from the dynamic loading of DOM elements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unable to achieve two-way binding with ng-model in textarea

I'm encountering a strange problem with AngularJS. I have a textarea with a default value, but when I manually change the value in the textarea, it isn't being updated in my controller. Additionally, the other scope is not binding to the default ...

Explaining the process of defining `this.props` and storing data in the global Redux state

I am currently diving into the world of react and Redux and I'm using a react project on GitHub called overcode/rovercode-ui as a learning tool for understanding react and Redux. As I explore this project, I have come across some intriguing questions. ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

JavaScript Class vs Function as Definition

Having trouble locating documentation for this issue. I devised a JavaScript class in the following manner: class Polygon { constructor(height, width) { this.height = height; this.width = width; } area = function() { return this.height ...

The success function in Ajax is constantly elusive, while the error function prevails. The data just can't seem to make it to the destination file

Thank you for your patience. This marks my initial post to the best of my recollection. The section below showcases a snippet from my calendar.js script. My current objective involves sending data obtained from a modal window in index.php over to sql.php. ...

What is the process for showcasing specific Firestore items on a webpage?

database I've encountered an intriguing bug in my code that is proving difficult to resolve. The code involves a straightforward setup with React and Firestore, where items are listed on one page and their details are displayed on the next. However, t ...

What is the best way to eliminate excess space on the right side in Bootstrap 4 while in mobile view?

I'm struggling to understand why this layout is not responsive on mobile devices, triggering a bottom scroll bar at around 616px. I'm looking for a solution to hide the scroll bar at least until 414px for iPhones and other smartphones. I've ...

MVC with StructureMap, Repository Layer, and Console/Class Library Integration

I have successfully implemented StructureMap for dependency injection in my WebApi application. The ApiController includes a repository with dependencies like IMapper and DB connection string injected in its constructor. The repository is located in a sep ...

What is the best way to incorporate variables into strings using JavaScript?

Can someone help me achieve the following task: var positionX = 400px; $(".element").css("transform", "translate(0, positionX)"); Your assistance is greatly appreciated! ...

Discovering a way to monitor keyup and keydown occurrences in JavaScript on an iPhone

Looking to track keyup/keydown events in JavaScript on iPhone browsers. My goal is to automatically move the focus to the next form element after the user has inputted the maximum number of characters in a text box. ...

Having trouble retrieving react environment variables from process.env?

When developing my React App, I utilized a .env file to securely store some essential API keys. However, as I attempted to access these variables using process.env, I encountered an issue where the values appeared to be set as undefined. To launch the app ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Can a web application be developed utilizing JavaScript to access the torch feature in Safari?

Currently working on a website that needs to utilize the flashlight feature on both android and IOS devices. Found a method to activate the torch from an android device using Chrome (link). However, this same code does not seem to be functional on my IOS d ...

Removing fragment identifier from the URL

If you go to stackoverflow.com/#_=_, the expression window.location.hash will display #_=_. All good so far. But when you run window.location.hash = '' to get rid of the hash, the URL changes to stackoverflow.com/#. (Note the unexpected # at the ...

Exploring Ways to Loop through a JavaScript Map in Angular with ng-repeat

As I work on developing my Angular application, I encounter a situation where I have a Map object with keys and values (as demonstrated below). These key-value pairs in the map object (headerObj) are provided by the user as input to the application. var ...

Retrieve a Google map using Ajax in a PHP script

I'm attempting to display a google map on my homepage using the following function: function addressCode(id, concatenatedToShowInMap) { var geocoder; var map; geocoder = new google.maps.Geocoder(); ...

Learn how to pass a JavaScript variable value to a PHP variable effectively

I have created a JavaScript variable and set it to a value. <script> var points = 25; </script> Now, I need to access this value in PHP for some specific reason but I am unsure how to accomplish that. ...

Tips for implementing a conditional statement within an export default clause

I am completely new to web programming and I'm attempting to create a question-answer feature using Vue.js. export default { // Trying to implement an if statement (if character == "Past", then do these steps) "steps": [ { ...

What does {``} denote in react-native programming?

During my participation in a collaborative project, I noticed that there is a significant amount of {' '} being used. For instance: <Text> {' '} {constant.Messages.PointText.hey} {this._user.first_name || this._user ...

Tips for determining the height of the entire webpage using jQuery

I attempted the following code: $(window).height(); $("#content").height(); However, it did not provide an accurate value. ...