Storing chrome identity api responses in a Vue.js component can be achieved by creating a function

When passing the response from the Chrome Identity API to the tab running my Vue-powered Chrome extension, I encountered an issue in storing this information inside my Vue instance for use within a component. Despite trying to assign the info to a variable using this.username, it consistently resulted in 'undefined' when viewed in the console. What could be wrong with the code and what is the best approach to resolving this?

Relating to the component code:

<script>
import { EventBus } from '../../event-bus';

export default {
  data () {
    return {
      socket: null,
      isRegistered: false,
      isConnected: false,
      username: null,
      message: '',
    }
  },
  created() {

  },
  mounted() {
    chrome.runtime.onMessage.addListener(
      function(request, sender){
      console.log(request);
      this.username = request.name;
      this.isRegistered = true;
    });
    EventBus.$emit('open-connection')
// The variable remains undefined and the open-connection event isn't emitted?
    console.log(this.username)
    EventBus.$on('connected', (socket) => {
      console.log(socket)
      this.socket = socket;
      this.isConnected = true;
      console.log(this.socket.id)
    })
  },
  methods: {
// Although I attempted to use this method, it does not get called within mounted, leading to errors :(
    connect(){
      
    }
    // other methods here 
  }
}
</script>

<style scoped>

</style>

The response obtained from the identity API contains various fields, which I will omit for privacy reasons:

{
  "id": "100xxxxxx",
  "name": "xxx",
  "given_name": "xxxx",
  "family_name": "xxxx",
  "picture": "https://lh4.googleusercontent.com/xxxxx.jpg",
  "locale": "xx"
}

Please note that accessing the response object using the key.val syntax is not possible.

EDIT

After some debugging efforts, I managed to find a solution. It turns out that the response information retrieved from the API is actually JSON data. By utilizing the JSON.parse() function, I was able to convert it into an object format, enabling me to access the fields using the key.value syntax successfully.

Answer №1

Instead of depending on the component's state, it may be beneficial to utilize chrome.storage for setting and retrieving data.

If not, could you please provide insights into what is outputted by console.log(request) and how the background script is structured?

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

I am interested in having the push notification feature function specifically for registered users

In an attempt to register the device for push notification using the PhoneGap plugin, I am encountering an issue. After the AJAX success action is called, the registration action does not alert the registration ID. Can someone help figure out what's g ...

Transforming a string into an object

I've been working on this code where my aim is to convert a string into an object and then display the data from an ajax call. However, it appears that using the string value in this way is not functioning as expected. var string = "first: 'Geor ...

What is the best way to determine when an IndexedDB instance has finished closing?

In the world of IndexedDB, the close method operates asynchronously. This means that while close finishes quickly and returns immediately, the actual connection closure happens in a separate thread. So, how can one effectively wait until the close operatio ...

VueX threw an error stating that it cannot read property 'getters' because it is undefined in Nuxt.js

Just starting out with Vuejs and Nuxt.js. I recently set up a Nuxt project but encountered an error when trying to run it: https://i.sstatic.net/ROtOs.png Any assistance would be greatly appreciated. Thank you. ...

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

Using Node.JS, Sequelize, and Moment.JS to format dates

Seeking help on formatting a date loaded from Sequelize in my database. I'm working on a blog and need to display the creation date of an article. Here's my route: app.get("/", (req,res) =>{ Article.findAll({ order:[ [ ...

Activating a link click inside a table with jquery

I have been attempting to trigger a click on an anchor within the table compareTable with the code below, however it does not appear to be working as expected. Would anyone be able to provide insight into a possible solution? $('#compareTable a' ...

The value of ng-repeat list in AngularJS does not update when its value is changed by an ajax call

I am completely perplexed. Why doesn't my ng-repeat update when there is an ajax call that changes its value? I have searched through many questions and answers here, but none of them address the issue with the ajax call. Here is the HTML: <div c ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

Hide the button when you're not actively moving the mouse, and show it when you start moving it

How can I make my fixed positioned button only visible when the mouse is moved, and otherwise hidden? ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...

Validating date parameter in Wiremock request - How to ensure dynamic date matching during testing?

Looking for some assistance in verifying that the date in a request is exactly Today. I've tried various methods from the documentation, but haven't achieved the desired outcome yet. Calling out to any helpful souls who can guide a junior QA thro ...

AWS Lambda with Node.js: Storing data during streaming - cuts short before completion leading to missing data

There's a Lambda function in my application that gets triggered whenever a new JSON file is written to an S3 bucket. The function is responsible for reading the contents of the JSON file, extracting individual records, and then storing them in a datab ...

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Extract information from a URL without the need for a page reload or user interaction

Recently, I developed a form that accepts YouTube links and extracts the ID using parsing/regex. The function is triggered by clicking a button, which then displays the ID of the URL. Is there a way to show the ID without requiring a button click or page ...

How to Use Jquery to Retrieve the Selected Option Value and Append a Parameter

I am attempting to expand the value by adding "&fullpage=true" <select name="navMenu" onchange="go(this.options[this.selectedIndex].value)"> <option value="-">Choose</option> <option value="page.html&amp;nyo=0" class="ccbnLnk" ...

I am encountering a "TypeError: topics.forEach is not a function" error when attempting to retrieve metadata for topics using my kafkajs client in Node.js/express.js. Can anyone help me understand why

I am attempting to retrieve the metadata of my Kafka brokers' topics using the kafkajs admin client within my Node.js + express.js server. Here is the content of my index.js file, serving as the main entrypoint for npm: 'use strict'; cons ...

Transform jQuery scroll script into vanilla JavaScript

While I am quite familiar with jQuery, I find myself struggling when it comes to using pure JavaScript. Could anyone provide guidance on how I can convert my jQuery code into vanilla JavaScript? Your help is greatly appreciated! Below is the code that I ...

Moving through content on a single page

import React, { Component, useState } from "react"; import { Content, List, ListItem, Left, Right, Icon, Container, Header, Body, Button, Title, } from "native-base"; //Chapter One expor ...

How to execute a JavaScript function within a Jinja for loop

I am currently working on an HTML page where the variable schedule contains a series of sequential decimal numbers representing seconds. My goal is to develop a function in JavaScript/jQuery that can convert these decimal numbers into time format. However ...