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.