Utilize a chrome extension to showcase specific content on designated webpages through the use of

I'm currently working on creating a Chrome extension for Pinterest integration.

After referencing some examples from the Chrome extension demo (specifically one that displays an icon in the omnibox when the URL contains a 'g'), I made modifications to make it work for URLs containing "pinterest.com". Here is the updated code:

manifest.json:

"permissions": [
    "tabs", 
    "http://*.pinterest.com/"
]

In background.js, I mostly replicated the example code found online:

function showPinterestAction(tabId, ChangeInfo, tab) {
  if(tab.url.indexOf('pinterest.com') > -1){
    chrome.pageAction.show(tabId);
  }
  /* This doesn't work. tab.url returns as undefined for me :( */
};

chrome.tabs.onUpdated.addListener(function(tabId, change, tab) {
  if (change.status == "complete") {
    showPinterestAction(tabId);
  }
});

chrome.tabs.onActivated.addListener(function(tabId, info) {
  selectedId = tabId;
  showPinterestAction(tabId);
});

// Ensure the current selected tab is set up.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  alert(tabs[0].id);
  showPinterestAction(tabs[0].id);
});

The issue I am facing is that the icon is not appearing on the correct page. When I try to alert(tab.url), it simply shows undefined. Could someone please help me identify what's wrong with my code?

Answer №1

When you call showPinterestAction, you are only passing in the tabId parameter.

As a result, it's not surprising that the tab parameter ends up being undefined. The function showPinterestAction is structured based on the tab update callback, but it seems like you're not utilizing it correctly.

To address this issue, consider updating the showPinterestAction function to retrieve the necessary data:

function showPinterestAction(tabId) {
  chrome.tabs.get(tabId, function(tab){
    if(tab.url.indexOf('pinterest.com') > -1){
      chrome.pageAction.show(tabId);
    }
  });
};

You may also want to broaden your match pattern to include various scenarios with "*://*.pinterest.com/*".


Alternatively, rather than relying on multiple tabs events, you can utilize the declarativeContent API, which is specifically designed for this purpose.

var rule = {
  conditions: [
    new chrome.declarativeContent.PageStateMatcher({
      pageUrl: { hostSuffix: 'pinterest.com' }
    })
  ],
  actions: [ new chrome.declarativeContent.ShowPageAction() ]
};

chrome.runtime.onInstalled.addListener(function(details) {
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([rule]);
  });
});

This approach eliminates the need for extensive permissions like "tabs" or host permissions. Your manifest file will only require:

"permissions": [
   "declarativeContent", 
   "activeTab"
]

in order for everything to function smoothly.

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

The audio directory is not included in the build of the Ionic framework, causing it to be skipped and absent

Recently, I've been working on an Ionic/Cordova app and came across a folder labeled /audio which consists of mp3 files: /www /assets /audio file.mp3 /css /js config.xml index.html The issue at hand is that the /audio directory is n ...

React Native: error - unhandled action to navigate with payload detected by the navigator

Having trouble navigating from the login screen to the profile screen after email and password authentication. All other functions are working fine - I can retrieve and store the token from the auth API. However, when trying to navigate to the next screen, ...

Switch the timezone to GB for all individuals accessing the page

My current code checks if a user falls within a specific time range (9.00am - 17.30pm) Monday to Friday. function checkTime() { var d = new Date(); // current time var hours = d.getHours(); var mins = d.getMinutes(); var day = d.getDay(); ...

Is there a way to retrieve an image from the Youtube search feature within a React application?

async function searchYouTube(query ) { query = encodeURIComponent(query); const response = await fetch("https://youtube-search-results.p.rapidapi.com/youtube-search/?q=" + query, { "method": "GET", maxResult: 2, "headers": { ...

Guide to Implementing a Single Trigger Click with jQuery for Window Scrolling

I have implemented JavaScript code for a button that loads additional posts from the database. The button has the class of .getmore. My goal now is to enable infinite scroll so that users do not have to manually click the button. In order to achieve this ...

Is there a way for me to retrieve the pageProbs that I have shared with a Component in _app.js?

Upon the loading of my website, I am fetching a large amount of data using getInitialProps. MyApp.getInitialProps = async (appContext) => { // Calls page's `getInitialProps` and fills `appProps.pageProps` const appProps = await App.getInitialProps( ...

Exploring the functionality of traversing in three.js for adjusting wireframes

I am dealing with multiple objects that have the ability to change their wireframe property to true or false at runtime when selected using a checkbox. function toggleWireFrame(obj){ var f = function(obj2) { if(obj2.hasOwnProperty("ma ...

What is the reason behind utilizing arrow functions in React event handlers?

function ButtonIncrement(){ const [count,setCount] = useState(0); render(){ <div> <h3> <button onClick={() => setCount(count+1)}>Increase count for amusement</button> <p>Total C ...

Avoid special characters (metacharacters and diacritical marks)

When my program consumes data from an API, it receives the following output: "<a href=\"http:\/\/www.website2.com\/\" target=\"_blank\">Item card<\/a>","<img src=\"https:\/\/website.com ...

What is the specific character code assigned to the "Enter" key on a

Check out this code snippet: http://jsfiddle.net/YttKb/ In my javascript, I am trying to add a new line of text using utf-8 coding. Which character should I use to make a new line? It seems like \n only creates a line break, not a new line of text. ...

Unable to modify background color in base website

While working on my project with Next.js, I encountered an issue where creating a button to change the color only affected the base web components' color and not the background color. _app.tsx import '../styles/globals.css'; import type { Ap ...

Certain scripts fail to load properly when using Internet Explorer

The code snippet provided only seems to be functional in Firefox, where it displays all alerts and successfully executes the displayUserLanding function. However, in Internet Explorer, the browser appears to only execute the following alert: alert("Helper ...

Top approach to locating an image's duplicate on a server and retrieving its file path

My current project involves developing a web application specifically for managing digital assets, focusing solely on image files. Upon uploading an image, the file is stored in a designated folder and a corresponding row is added to a MySQL database with ...

Update the displayed image on the webpage based on information retrieved from the database

Can someone help me figure out how to change the clickable icon on getseats.php from available to unavailable when a seat's status is 0? I'm struggling with this and any advice would be appreciated. Here's the code I have: <?php $noerro ...

Issue with redirecting after a POST request is not functioning properly

After creating an API in node and defining a method to handle POST requests, I found that returning res.redirect(redirectUrl); from the method causes the browser to redirect back to the API instead of the intended URL. Despite my efforts, this issue persi ...

The latest version of Chrome 121.0.6167.185 is causing issues with the Web Driver Manager by Boni Garcia

After the recent Chrome update to version 121, I've been experiencing issues running my Selenium tests. Despite updating both Selenium and BoniGarcia WebDriver Manager to the latest versions, the problem persists. The error message I'm getting is ...

Vue Array Proxy Class Fails to Trigger Reactivity

My custom Array extension has a feature where it intercepts changes made to its properties using Proxy, which is returned from the constructor. However, when used in a Vue component, it encounters issues. For example, when a filter is added, the display do ...

When the user clicks, show a designated search result in a separate container

I've been developing my Angular cocktail application, and I've reached a point where I can display all the cocktails in my database (only showing names). Now, I want to implement a feature where if I click on a specific cocktail, its full content ...

I am interested in showcasing only the week and day in the FullCalendar plugin

I have been working on customizing the fullcalendar plugin in JQuery which can be found at arshaw.com. By default, this plugin displays the entire month and week. However, I am specifically interested in only displaying the week and day views. Even after ...

Issues with Imported Routes Not Functioning as Expected

I am currently working on implementing routing in my Angular 2 project. All the components are functioning properly, but I encounter an error when I include 'appRoutes' in the imports section of app.module.ts. An unexpected TypeError occurs: C ...