Creating a WebExtension using Angular and TypeScript

I am currently working on creating a WebExtension using Angular and Ionic. The extension successfully loads the application and enables communication between Content Script and Background Script. However, I am facing an issue where the TypeScript code is not being interpreted correctly, leading to difficulties in storing data in the application variables. My goal is to extract webpage content into my Angular application. Is this technically feasible? Any assistance would be greatly appreciated. Thank you for your help.

manifest.json :

{
  "manifest_version": 2,
  //[...]
  "background": {
    "page": "index.html#/background"
  },
  "content_scripts":
  [{
    "matches" : ["<all_urls>"],
    "js": ["content_script.js"]
  }]
}

content_script.js :

browser.runtime.sendMessage({url: location.href});

Background Script (Angular) :

ngOnInit() {
    var browser = browser || chrome;
    browser.runtime.onMessage.addListener(this.showMessage);
}

public url: string;
showMessage(message) {
    alert(message.url); // This works
    this.url = message.url;
    alert(this.url); // This does not work
}

Answer №1

Issue resolved!

Although I can't offer a detailed explanation, the following line seems to be significant:

browser.runtime.onMessage.addListener(this.showMessage);

This snippet of code essentially does the same thing as the one below:

browser.runtime.onMessage.addListener(function(message) {
    alert(message.url); // It functions correctly
    this.url = message.url;
    alert(this.url); // Doesn't seem to work
});

The use of arrow functions in TypeScript affects how they are interpreted, so calling the method like this was necessary:

browser.runtime.onMessage.addListener((message) => {
  this.url = message.url;
  alert(this.url); // It works now
});

If you need to implement the "background" route using the Ionic framework, here is an example of the required code:

const links: any = [
  { component: Page, name: 'Background', segment: 'background' }
];

@NgModule({
  declarations: [],
  imports: [
    IonicModule.forRoot(MyApp, {}, {links})
  ],
  bootstrap: [],
  entryComponents: [],
  providers: []
})

For TypeScript type definitions related to WebExtensions, refer to this link: https://github.com/michael-zapata/web-ext-types

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

Error occurred while attempting to run 'postMessage' on the 'Window' object within GoogleTagManager

Recently, I encountered an error stating "postMessage couldn't be cloned". This issue seems to be affecting most of the latest browsers such as Chrome 68, Firefox 61.0, IE11, and Edge. Error message: Failed to execute 'postMessage' on &ap ...

Could someone shed some light on why my code within the useEffect hook in my component is being triggered twice when it shouldn't be?

I'm currently developing a VR Web project using Three.js within a React-Vite-Typescript setup. As I begin this new project, my focus is on coding the initial view. It starts with a black screen displaying a white logo at the center, reminiscent of in ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...

What are the best practices for integrating Firebase authentication pre-made UI in Next JS?

As someone new to React and NextJS, I am eager to implement an authentication service for my NextJS web application in order to manage user accounts efficiently. I am particularly interested in utilizing a familiar user login solution that offers a compre ...

Adjust the color of the paper in Material-UI

I'm in the process of creating a React project using the material-ui library. Currently, I am facing an issue with customizing the drawer component's background color. After some research, I learned that modifying the paper attribute of the drawe ...

Word.js alternative for document files

I'm on the lookout for a JavaScript library that can handle Word Documents (.doc and .docx) like pdf.js. Any recommendations? UPDATE: Just discovered an intriguing library called DOCX.js, but I'm in search of something with a bit more sophistic ...

Issues with Sound Not Playing When Button is Clicked in Python Flask

My goal is to trigger an audio sound when the Delete button is clicked. I've created an external JavaScript file and successfully linked it with Flask. index.html <a href="/delete/{{todoitem.item_id}}" class="btn btn-danger" onclick="playDelSound ...

encountering problems with Next.js routing resulting in 404 errors

I developed a Next Js 14 app where I had to change the routing names inside the pages before going live. For example, instead of 'Charts', I changed it to 'charts' and made similar modifications to other pages as well. However, after de ...

What are the advantages of combining the website URL and API URL within the Angular service?

When deploying my application in a production environment, I encounter an issue with the URL addresses. The web address is , while the API address is . However, when making a request to the API through Angular, the URLs get concatenated into . This issue d ...

Exploring .ENV Variables using Angular 2 Typescript and NodeJS

After completing the Angular2 Quickstart and tutorials, I'm now venturing into connecting to a live REST Api. I need to include authentication parameters in my Api call, and from what I've gathered, it's best practice to store these paramete ...

Calculate the date and time three months before or after a specified date

I have the following start date : 2023-09-03T00:00:00+05:30 and end date : 2023-09-10T00:00:00+05:30 My objective is to deduct 90 days from the start date and add 90 days to the end date Afterwards, I need to convert it to UTC format In order to achieve ...

Get rid of the strange border on the material dialog

I am struggling with the Angular material 6 dialog component as it is displaying a strange border. I have attempted to remove it using the code below, without success. Interestingly, when I apply the style inline in the browser, it works fine. Any suggesti ...

What Causes the "Do Not Push Route with Duplicated Key" Error in React Native with Redux?

I have successfully integrated Redux into my React Native project, specifically for navigation purposes. Below is the code snippet from my navigation reducer file (navReducer.js): import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes' ...

Experiencing delays with Angular 4 CLI's speed when running ng serve and making updates

After running ng serve, I noticed that the load time is at 34946 ms, which seems pretty slow and is impacting our team's performance. Additionally, when we update our code, it takes too long to reload the page. https://i.sstatic.net/lpTrr.png My Ang ...

Selenium htmlUnit with dynamic content failing to render properly

My current project involves creating Selenium tests for a particular website. Essentially, when a user navigates to the site, a CMS injects some dynamic elements (HTML + JS) onto the page. Everything works fine when running tests on the Firefox driver. H ...

Issues with Ionic 3 Directive Not Functioning

Struggling to create a custom directive in Ionic that won't resize automatically? I can't figure out what's going wrong. Here's the code snippet from my project, which is an Ionic 3 app with Angular 4: import { Directive, HostListener ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Ajax UpdateProgress not functional

How can I resolve the issue where my AJAX UpdateProgress bar in ASP.NET is not running when executing a query in the correct format upon button click? Any solutions or help would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtml"> ...

Storing Node_modules in a separate directory

All my node modules are located in the path C:/Users/user/AppData/Roaming/npm/node_modules. I am attempting to include these node modules with babel and babel-presets for my webpack scripts. Here is my webpack.config.js module.exports = { context: &a ...

AngularJS enables box to smoothly slide up and down when hovered over

I am attempting to create a div that will overlay an image on hover with a slide up and slide down effect. Can anyone provide guidance on how to achieve this without relying on jQuery? I would prefer to utilize only AngularJS in my application. Here is a ...