VueJS Chrome extension that redirects the current tab to a new URL

Hello everyone, I'm currently working on a Chrome extension using VueJS and I need help. I want to implement a feature where clicking a button in the extension will redirect the current tab to a new URL. I followed the approach mentioned by someone on StackOverflow at this link:

Unfortunately, it didn't work as expected and I'm not sure if it's due to a faulty implementation or if it simply wouldn't work in my case.

Here is a snippet of my code:

ProductList.vue

I'll only share the script part as it's crucial for this issue. The script is running because when I click the button, it prints out the URL.

<script>
export default {
  name: "ProductList",
  props: {
    items: Array
  },
  methods: {
    shopProduct(url) {
      console.log(url);
      chrome.runtime.sendMessage('open-product-url')
    }
  }
}
</script>

Manifest.json

{
  "manifest_version": 2,
  "name": "__MSG_extName__",
  "homepage_url": "http://localhost:8080/",
  "description": "A Vue Browser Extension",
  "default_locale": "en",
  "permissions": [
    "tabs",
    "<all_urls>",
    "*://*/*"
  ],
  "icons": {
    "16": "icons/16.png",
    "48": "icons/48.png",
    "128": "icons/128.png"
  },
  "browser_action": {
    "default_popup": "/app.html",
    "default_title": "__MSG_extName__",
    "default_icon": {
      "19": "icons/19.png",
      "38": "icons/38.png"
    }
  }
}

Background.js

chrome.runtime.onMessage.addListener(
    (message, sender, sendResponse) => {
        console.log(sender.id);
        console.log(sender.tab.id);
        sendResponse(true);
    }
)

vue.config.js

module.exports = {
  pages: {
    app: {
      template: 'public/app.html',
      entry: './src/main.js',
      title: 'App'
    }
  },
  pluginOptions: {
    browserExtension: {
      componentOptions: {
        background: {
          entry: './src/assets/js/background.js'
        },
        contentScripts: {
          entries: {
            'content-script': [
                './src/assets/js/contents.js'
            ]
          }
        }
      }
    }
  }
}

Currently, I have only attempted to display the sender ID as I plan to update the URL later on and will require the sender tab ID.

Answer №1

Solved the issue independently.

Resources I utilized to overcome the challenge:

Instead of placing the listener in background.js, it should have been written in contents.js. Additionally, within the vue component, utilizing a query and sending the message as shown below fixed the problem:

browser.tabs.query({ active: true, currentWindow: true }).then(tabs => {
        browser.tabs.sendMessage(tabs[0].id, {
          msg: { action: "change_body_color", value: 'hello' }
        });
      });

Answer №2

Utilize the Chrome API with this method, Chrome.tabs.update

Background.js

chrome.runtime.onMessage.addListener(
    (message, sender, sendResponse) => {
        console.log(sender.id);
        console.log(sender.tab.id);
        chrome.tabs.update(sender.tab.id, {
            url: '<new_url>',
        });
        sendResponse(true);

    }
)

For more information, visit: Update and run pre-defined link on current tab chrome extension

Reference https://developer.chrome.com/docs/extensions/reference/tabs/#method-update

Suggestion

  • If you have <all_urls> permission, there is no need for "*://*/*" permission.

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

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Node code on the server side that emits a socket

I am currently using the MEAN stack, with AngularJS on the frontend and Node.js on the backend. Can I trigger a socket emit call within certain functions? My primary focus is to send data to the client side exclusively. Alternatively, how does a server-s ...

Ways to retrieve the current state within a function after invoking the setState method

I'm currently working on a function to store the blogPost object in a document within my Firestore database. The process I have in mind is as follows: Click on the SAVE button and initiate the savePost() function The savePost() function should then ...

Steps to retrieve the value of a particular row in a table using vuejs

Can you help me retrieve the value of a specific row in a table using VueJS 2? Here is an image of my current table: https://i.sstatic.net/jb1uw.png I need assistance with obtaining and displaying the last value from a loop in the "SHOW QR Button" within ...

What sets local Node package installation apart from global installation?

My curiosity sparked when I began the process of installing nodemon through npm. Initially, I followed the recommended command and noticed the instant results displayed on the right side of my screen: npm i nodemon This differed from the installation ins ...

Difficulty transferring form information to PHP utilizing Ajax

Originally, I had a traditional HTML form that submitted data through a button, redirecting the user to the page where the PHP code ran successfully. Now that everything is functioning as expected, I aim to pass the form variables to PHP using Ajax in ord ...

Utilizing React to implement a search functionality with pagination and Material UI styling for

My current project involves retrieving a list of data and searching for a title name from a series of todos Here is the prototype I have developed: https://codesandbox.io/s/silly-firefly-7oe25 In the demo, you can observe two working cases in App.js & ...

Using AngularJS to dynamically populate a dropdown menu from a JSON object

I am a beginner to Angular and currently facing my first significant challenge. The JSON object below is the address data retrieved from a third-party API and added to $scope.AddressData in a controller: $scope.AddressData = [{ "Address1":"South Row", ...

Add a class if the particular class is missing from the webpage

Seeking a solution in JS, I am facing a challenge in creating a series of elements with active states, each opening a caption below when clicked. Utilizing .addClass, .removeClass, and .toggleClass in combination, only one element can be active at a time. ...

Access a document from a collaborative directory directly in a web browser

When I paste the shared path for a PDF file into the address bar, it opens perfectly in all browsers. The code below works fine in IE 8 but not in Chrome and Firefox. Code: function openPDF(file) { window.open(file, '_blank'); } function link ...

remove website tracking data by using developer tools console

In JavaScript, we have the ability to delete local storage or session storage items using the clear() method: localStorage.clear(); sessionStorage.clear() However, is there an equivalent method like cookies.clear() to clear cookies? If so, how can it be ...

Incorporate numerous style classes into an object using React Material-UI

I am facing an issue with my JSX code: <span className="btn-pause btn"><i class="fa fa-pause"></i></span> I would like to change the color of this button. Here is what I have tried: const styles = { btncolor ...

Submitting data via AJAX using the method parameter

I have a specific ajax form that requires serialization and the manual setting of the _method for the data form. This is how I am currently handling it. $.ajax({ url: http://someposturl.com/object, type: 'POST', ...

Node.js Dynamic JSON References

In my JSON file "jFile", the structure is as follows: { "Entry1": null, "Entry2": "SomeValue" } I have some node.js code that successfully updates the file content like this: jFile.Entry1 = "SomeText"; fs.writeFileSync( "jFile.json", JSON.stringif ...

Express req.files returns null when using jQuery FormData

For client side functionality, I am utilizing Bootstrap and jQuery. On the server side, my technology stack includes node.js and express. The form structure is displayed below: <form id="signupform" action=""> <h2&g ...

Updating Text in Textarea upon Selection Change

Need assistance with updating the content of a textarea based on a select option change. Below is an example of my code: <tr><td>Template:</td><td> <select t name="template" onChange = "setTemplate();"> <option ...

Guide on transforming the popup hover state into the active state in vue.js through a click event

My code currently includes a popup menu that shows up when I hover over the icon. However, I need to adjust it so that the popup changes its state from hover to active. Intended behavior: When I click the icon, the popup should appear and then disappear w ...

Update the text on Bootstrap Tooltip when it is clicked

I am looking to update the content of my tooltip when it is clicked. Below is the current code snippet I am using: function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); ...

The number THREE was not identified within the specified brackets

Here is the code snippet I am working on: var camera, scene, renderer; var mesh; var x, y, z; function init() { "use strict"; renderer = new THREE.WebGLRenderer(); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.i ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...