Leveraging the power of Vue.js and a Chrome extension to extract information from a background

After following a tutorial on creating a Chrome extension with Vue.js, I successfully implemented a Vue.js based extension. Now, my goal is to pass the URL of an active tab from a background script to the popup page.

I added console.log statements in the onMessage and onClicked events in background.js, but these listeners seem not to be receiving any data. Strangely, the onInstalled listener is working perfectly.

Given that I'm relatively new to both Vue.js and browser extensions, I'm feeling a bit lost here. Could you assist me in identifying what might be missing or incorrect in my code?

manifest.json

{
    "manifest_version": 3,
    "name": "Random Quote",
    "version": "1.0.0",
    "description": "Browser extension that fetches a random quote from zenquotes.io",
    "host_permissions": ["https://zenquotes.io/"],
    "permissions": ["activeTab", "scripting"],
    "action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/icon-16x16.png",
        "48": "images/icon-48x48.png",
        "192": "images/icon-128x128.png"
      }
    },
    "background": {
      "service_worker": "js/background.js"
    }
  }

background.js

chrome.runtime.onMessage.addListener(function () {
  console.log("onMessage.addListener");
});

chrome.action.onClicked.addListener(function (tab) {
    console.log("onClicked.addListener");
});

chrome.runtime.onInstalled.addListener(() => {
  console.log('Hello, World!');
});

popup.html

<!DOCTYPE html>
<html lang="en_US">
  <head>
    <title>Random Quote</title>
    <link rel="stylesheet" type="text/css" href="css/popup.css" />
    <meta charset="UTF-8">
  </head>
  <body>
    <div id="app"></div>
    <script src="js/popup.js"></script>
  </body>
</html>

popup.vue

<template>
    <div class="container">
      <h1 class="title text-center">Random Quote</h1>
      <blockquote class="quote-card">
        <p>
          {{ state.quote }}
        </p>
  
        <cite> {{ state.author }} </cite>
      </blockquote>
      <blockquote class="quote-card">
         here show URL of the current Tab 
      </blockquote>
    </div>
  </template>
  <script>
  export default {
    data() {
      return {
        state: {
          quote: "",
          author: "",
        },
      };
    },
    async created() {
      try {
        const response = await fetch("https://zenquotes.io/api/random");
        const data = await response.json();
  
        if (Array.isArray(data) && data.length > 0) {
          this.state.quote = data[0].q; // Extract the quote from the response
          this.state.author = data[0].a;
        } else {
          this.state.quote = "Failed to fetch quote.";
        }
      } catch (error) {
        console.error(error);
        this.state.quote = "Error occurred while fetching quote.";
      }
    },
  };
  </script>

popup.js

import { createApp } from "vue";
import Popup from "./Popup.vue";

console.log("popup.js - 1");
createApp(Popup).mount("#app");
console.log("popup.js - 2");

webpack.mix.js

let mix = require("laravel-mix");

mix
  .setPublicPath("./")
  .sass("src/sass/popup.scss", "dist/css")
  .js("src/js/popup.js","dist/js")
  .js("src/js/background.js","dist/js")
  .vue()
  .copy("src/images/", "dist/images")
  .options({
    processCssUrls: false,
  });

mix-manifest.json

{
    "/dist/js/popup.js": "/dist/js/popup.js",
    "/dist/js/background.js": "/dist/js/background.js",
    "/dist/css/popup.css": "/dist/css/popup.css",
    "/dist/images/icon-128x128.png": "/dist/images/icon-128x128.png",
    "/dist/images/icon-16x16.png": "/dist/images/icon-16x16.png",
    "/dist/images/icon-48x48-off.png": "/dist/images/icon-48x48-off.png",
    "/dist/images/icon-48x48.png": "/dist/images/icon-48x48.png"
}

package.json

{
  "name": "randomquote",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --env=production --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cross-env": "^7.0.3",
    "laravel-mix": "^6.0.49",
    "postcss": "^8.4.33",
    "sass": "^1.70.0",
    "sass-loader": "^14.0.0",
    "vue": "^3.4.15",
    "vue-loader": "^17.4.2",
    "vue-template-compiler": "^2.7.16"
  }
}

Answer №1

My attempt to transfer 'chrome.history.search' into 'popup.vue' seems almost successful. I managed to print URLs in the console, but hit a roadblock when trying to populate the 'history_items' property with URLs from the history within the chrome.history.search context. An error popped up indicating that history_items is undefined. However, I can successfully populate this property outside of this particular block. Any thoughts on what might be causing this issue?

popup.vue

<script>
export default {
  data() {
    return {
      state: {
        quote: "",
        author: "",
      },
      history: [],
      history_items: []
    };
  },
  /*   created(){
    this.fetchHistory()
  }, */
  mounted() {

    //this.save();
    this.fetchHistory();
  },
  methods: {
    save() {
      console.log("--save--");
      this.history_items.push("a1");
    },
    fetchHistory() {
      console.log("--fetchHistory--");
      this.history.push("b1");
      console.log("1-this.history_items->" + this.history_items)
      //here I am ok : 1-this.history_items->
      console.log("--this.history.push-- ok");

      chrome.history.search({ text: "", maxResults: 10 }, function (historyItems) {
        for (let item of historyItems) {
          console.log(item.url);
          console.log("2-this.history_items->" + this.history_items)
          //here I am getting : 2-this.history_items->undefined
          this.history_items.push(item.url);
          //here I got the error :Error handling response: TypeError: Cannot read properties of undefined (reading 'push')         
        }

      });
    },
  },

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

Tips for creating a reactive localStorage in a react application

I am utilizing localStorage to store user data upon login. The data is saved under the name "jwt_data". I have implemented a separate function in a JavaScript file to retrieve this data: export const auth = () => { if(localStorage.getItem('jwt_da ...

Encountering a data retrieval issue when using the useSWR hook in a project using reactjs

I am trying to retrieve data from the backend using useSWR. However, I have encountered two bugs in the function getDataUseSWR. The errors occur at line 'fetch(url).then': 1: "Expected 0 arguments, but got 1."; 2: "Property 'then' does ...

Vuex action fails to receive response from Axios

I have been attempting to use Axios to make a GET request to an API endpoint, but I am not receiving any response. I have tried placing the Axios call both in the component and in the Vuex store, but so far, I have had no success. store.js import Vue fr ...

How can I incorporate a JavaScript module into my Typescript code when importing from Typeings?

Exploring Angular2 and Typescript with the help of mgechev's angular2-seed for a new project has been an interesting experience. However, I have encountered a problem along the way. My intention is to incorporate Numeral into a component, and here ar ...

Tips for changing the page URL upon click in a Vue.js application

I am currently developing a post board application using Vue.js and I am facing an issue with redirecting the page when a user clicks on each post. To handle this, I have made use of vue-route and axios in my project. Here is a snippet from index.js, ex ...

An unexpected error occurred while parsing the JSON document: "unexpected token: '{'"

I'm facing an issue where I need to specify a URL in a JavaScript app that retrieves weather data from an API. The URL is constructed using a string and some variables. When I initially wrote the code below, I encountered the error message Missing { b ...

Vue parent component not receiving events properly

Referring to these sources: Forum Post Stack Overflow Question In my project, I am utilizing: CodeSandbox Example The setup involves the parent component listening for events emitted by a child component: mounted() { this.$on("edit-category& ...

What is the best way to output a received HTML page from the server?

I'm currently working on printing an HTML page that was generated using Node.js on my server. After sending the page to the client side as a response to an AJAX request, I have stored it in a JavaScript variable. var resp_json = printRequest.getRespo ...

associating functions with various events that require arguments

I am working with two event listeners that trigger separate functions, but I believe it might be more efficient to have them trigger the same function instead. These event listeners are monitoring keystrokes and the mouse wheel. $(document).mousewheel(on ...

The size of jVectorMap is displayed too diminutive

Why isn't my jVectorMap adjusting to the new height I've specified for the containing div? It only displays at the default height of 54px. Within a document.ready function in my scripts.js file, I have the following code: $('#team-map-usa& ...

Is there a way to use jQuery to gather checkboxes and add the selected ones to an array?

How can I efficiently collect values of checked checkboxes with a specific classname and store them in an array? Here is the current approach: var a = new Array(); $('.categoriesCb').each(function(i, item) { if ($(item).prop('checked&apos ...

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...

Utilize jQuery function within an HTML form

I am trying to integrate my jQuery function with an HTML tag for my login form that connects to an Azure database. I want a modal pop-up to appear when the client presses the Login button, displaying a specific message based on whether the user is in the d ...

Struggling to implement Google OAuth in a MERN stack - facing a 400 bad request error with the package @react-oauth/google

Here is the React form and relevant code sections for the issue: import { useGoogleLogin } from '@react-oauth/google'; const SignUpForm = () => { const navigate = useNavigate(); const [name, setName] = useState(""); const [email, setEm ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

Leveraging nodemailer and handlebars for personalized email templates

I'm encountering an issue and struggling to pinpoint what exactly is causing it. Whenever I execute my code, the following error message pops up: [Error: ENOENT: no such file or directory, open 'C:\Users\Alex\Desktop\emailtes ...

Slowly revealing sticky navigation with slideDown animation using JQuery

Here is the code for a .JS file: $(document).scroll(function (){ var menuheight= $('header').height(); var y = $(this).scrollTop(); if (y>(menuheight)) { $('.menu_nav_features').addClass ...

How should one go about editing the vertices of a box geometry?

I have been customizing the vertices of various box geometries to create unique shapes or adjust their heights. Everything looks great in my scenes (check out this example https://i.sstatic.net/w7Z3G.jpg). However, I encountered an issue when using the Ob ...

Searching for a specific element in jQuery by querying a string

I have a situation where an ajax request is made to send text using the POST method to another PHP page. This PHP page then converts the text into markdown format and sends it back. Here's an example of what it looks like: "<p>Meep, meep, <e ...

Issue with sharing on Facebook via direct URI

I'm currently working on implementing an FB share button on my website. When a user clicks on the button (which features the FB image), they are redirected to . I am dynamically setting the URL as location.href through JavaScript, and the URL is autom ...