0

thanks to all in advanced.

I'm trying to build a simple Chrome extension with vue using this Boilerplate, but I find it hard to communicate with the content.js file and popup.js file and passing data between them.

currently I'm trying to pass the total number of p tags that are in the current tab. when I try to invoke a method inside the sendMessage function I'm getting an Error saying this.count is not a function. I'v figured out that probably the function is not firing because it's nested, but I cant figure out how can invoke the method.

Cheers to all

popup.js

<template>
  <div>
    <p>{{title}}</p>
    <button v-on:click="getCount">click Here</button>
    <p>{{counts}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "count board",
      counts: ""
    };
  },
  methods: {
    getCount() {
      chrome.tabs.query({ currentWindow: true, active: true }, tabs => {
        chrome.tabs.sendMessage(tabs[0].id, "null", this.count);
      });
    }
  },
  count(res) {
    console.log(res.count);
    this.counts = res.count
  }
};
</script>

Content.js

chrome.runtime.onMessage.addListener(function (req, sender, sendResponse) {
    const para = document.querySelectorAll('p')
    sendResponse({ count: para.length })
})

I'm trying to invoke this.count on every button click in popup.html and retrieving the total numbers of P tags

Osh
  • 75
  • 9
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – wOxxOm Apr 17 '20 at 13:48
  • Replace `function(tabs){` with `tabs=>{` P.S. your count() doesn't return anything though... – wOxxOm Apr 17 '20 at 13:48
  • @wOxxOm thanks mate, but still this doesn't resolves the issue. regrading the count method I know I'm currently want to see if its working, but its even not console logging anything – Osh Apr 17 '20 at 14:09
  • Yep I know I'v `inspected` the popup to open the popup console – Osh Apr 17 '20 at 14:29
  • You **invoke** `this.count()` without any parameter so `res` is undefined. It's unclear what you're trying to do. Looks like you're confusing function invocation with function reference: you need to remove `()` to make it into a callback. – wOxxOm Apr 17 '20 at 14:33
  • [What is the difference between a function call and function reference?](https://stackoverflow.com/a/15886331) – wOxxOm Apr 17 '20 at 14:33
  • @wOxxOm cheers you are right I wasn't clear. I will check those link right now. Iv updated the question with more info maybe now its more clear – Osh Apr 17 '20 at 14:41

0 Answers0