When activated, the Chrome extension runs automatically instead of waiting to be clicked

Below is the content of my manifest.json file:

{
    "manifest_version": 2,   

    "name": "PageEscape",
    "version": "1.0",
    "description": "",

    "background": {
        "scripts": ["background.js"]
    },

    "browser_action": {
        "default_icon": "escape_icon.png"
    }
}

Additionally, here is the code inside my background.js file:

chrome.browserAction.onClicked.addListener(window.open("url", "_blank"))

The objective behind my Chrome extension is to provide users with a quick way to switch to another page, which I have initially selected. However, an issue arises when I enable the extension as it automatically redirects to the chosen webpage, and clicking on the extension icon in the browser does not function as intended. What modifications should I make to resolve this problem and achieve the desired functionality?

Answer №1

chrome.browserAction.onClicked.addListener( () => {
    window.open("newUrl", "_blank");
});

Answer №2

Here is an example of how you could do it:

const website = 'http://www.example.com/'
chrome.browserAction.onClicked.addListener(function(tab) {
  openWebsite(website);
});

/**
 * Open the specified website, handling three cases:
 * 1. If the website is already open, select it;
 * 2. If there is a new tab available, open the website in that tab;
 * 3. Otherwise, open a new tab in the current window.
 *
 * @param website
 */
function openWebsite(website) {
  chrome.tabs.query(function (tabs) {
    let newTab = null;

    // Iterate through all tabs
    for (let i = 0; i < tabs.length; i++) {
      let tab = tabs[i];

      if (tab.url === website) {
        chrome.tabs.update(tab.id, {url: website, selected: true});
        return;
      } else if (tab.url === 'chrome://newtab/') {
        newTab = tab;
      }
    }

    if (newTab) {
      chrome.tabs.update(newTab.id, {url: website, selected: true});
    } else {
      chrome.windows.getCurrent(function (win) {
        let winId = win.id;
        chrome.tabs.create({windowId: winId, url: website});
      });
    }
  });
}

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

Unable to delete the vendors directory generated by Webpack

I'm sorry, but I can't quite recall the exact process of how this directory was created. What I do remember is that I was experimenting with using chunks. Now, there's this vendors~. directory that webpack created, but for some reason, I ca ...

Technique for identifying a sequence within a longer numerical series

As I ponder this puzzle for what seems like an eternity, I humbly turn to you for a possible solution. A lengthy number resembling this one: 122111312121142113121 It is crucial to note that no numbers exceed four or fall below one. Now my quest is to une ...

Why is it that this JavaScript isn't working as intended in the popup form?

</br> s_foot"> * use ajax.jquery as control event. like $("#save").click(function(){.....}); <script type="text/javascript>" var wp; var position; var pid; var product_name; var production_date; In this script, I am attempting to re ...

Utilize TinyMCE in your WordPress plugin

How can I integrate TinyMCE into my WordPress plugin? I have a textarea in the backend script that I would like to convert into a TinyMCE WYSIWYG editable field. Is there a method to achieve this? The following code snippet is not yielding the desired re ...

Display a list of years by iterating over a computed property in Vue JS

Currently, I have a code snippet that displays a list of years. It seems to me that this code is a bit excessive, and I believe that implementing a computed property for validYears would streamline the code and eliminate the need for unnecessary watchers. ...

Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads. Here is the JavaScript code: var root = document.querySelector(':root ...

Facing issues connecting to my MongoDB database as I keep encountering the error message "Server Selection Timed Out After 3000ms" on MongoDB Compass

I am encountering an error on my terminal that says: { message: 'connect ECONNREFUSED 127.0.0.1:27017', name: 'MongooseServerSelectionError', reason: TopologyDescription { type: 'Single', setName: null, maxS ...

AgGrid Encounters Difficulty in Recovering Original Grid Information

After making an initial API call, I populate the grid with data. One of the fields that is editable is the Price cell. If I edit a Price cell and then click the Restore button, the original dataset is restored. However, if I edit a Price cell again, the ...

Optimal method for implementing an arrow function within a React class component while utilizing setState

I'm currently exploring the distinction between two approaches to using an arrow function and updating state in a React class component. Both methods appear to be functional in correctly updating the state. Within a controlled component, the function ...

Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example: { "totalCount":"4", "data":[ {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...}, {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","even ...

What is the proper way to display the complete result of aggregating each outcome from the previous iteration within two nested queries in an array using NodeJS and Mongoose?

As a newcomer to both Stackoverflow and NodeJS/Mongoose, I apologize if I make any mistakes or break any rules. Thank you in advance. I'm looking for a function that can return all nearby products based on my current location, which is provided by th ...

Error: Unable to locate the 'react' module in the specified directory

During the execution of my project, I encountered an error that read: Module not found: Can't resolve 'react' in I attempted various solutions to fix this issue. Initially, I ensured that the state in my component was correct and that I had ...

Creating a bot that will only respond once when a user sends multiple photos simultaneously

I'm currently working on a Telegram bot using nodejs. I am utilizing the node-telegram-bot-api library and have implemented the on('photo') method to handle when a user sends a photo to my bot. However, I am facing an issue where if a user ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

The functionality of the calculator, created using HTML and JavaScript, is impeded on certain devices

I developed a web-based app that functions as a simple calculator for calculating freight/shipping prices to Venezuela. The app allows users to select between 1 to 4 packages, and choose different types of freight including air (normal, express) and mariti ...

Choose2 generateUniqueEntry identification from submission

I am currently using select2 for a tagging input, but I am facing some challenges when it comes to handling the creation of new tags and retrieving the new tag IDs back into the select2. This issue is closely tied to another question on this topic which c ...

What steps should I take to address this particular issue in react native?

OOPS: The build did not go as planned! What went wrong: Could not access settings generic class cache for settings file 'C:\Users\subug\OneDrive\Desktop\React CLI Project\FirstProject\android ...

When working with Express router callbacks, the Array.includes() method will always return false, the Array.indexOf() method will always return -1, and

After utilizing fs.readFile() and fs.readFileSync() functions to access the content of 'words_alpha.txt', I discovered that the file can be accessed publicly from this link: https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha. ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...

Is it possible for me to interact with different elements upon hovering?

html, <div id="first"> <a>Click here</a> </div> <div id=second"> second div content </div> css, #first a:hover{ color:blue; /*change color on hover */ #second{ background:blue; } } In ...