How can I create a top-notch chrome extension to enhance shopping deals?

I am in need of creating a Chrome extension that will showcase the latest offers and coupons whenever I visit any affiliate store like Amazon, AliExpress, Flipkart, Myntra, etc.

Upon visiting their website with my extension installed, a popup with offers and coupons from that particular site should be displayed. (I have a webservice to fetch these offers and coupons).

The concept is illustrated in the image below. https://i.sstatic.net/QoUzb.png

I have experimented with something similar, but I'm not certain if it's the correct approach.

From Manifest.json

    "content_scripts": [
        {
          "matches": ["*://*/*"],
          "js": ["jquery.js","myscript.js"],
          "css":["offers.css"]
        }
    ],
    "web_accessible_resources":[
        "offers.html",
        "offers.js"
    ]

myscript.js

var url = chrome.extension.getURL('offers.html');
var iframe = "<iframe src='"+url+"' id='IframeID'></iframe>";
var host = window.location.host;
var splittedHost = host.split('.');
var title = $(document).find("title").text();
if(title != ''){
    $('body').append(iframe);
}

offers.html

<html>
<head>
    <meta charset="UTF-8">
    <title>test| Latest Offers</title>
    <script src="jquery.js"></script>
    <script src="offers.js"></script>
</head>
<body id="bodyText">
    <h1>
        Welcome
    </h1>
    ...
</body>
</html>

With this setup, I see something similar to this on every page I visit:

https://i.sstatic.net/B0dJW.png

The iframe actually represents the offers page, and to retrieve offer data, I require the hostname from the URL. When trying to obtain window.localtion.host within offers.js injected into offers.html, I receive chrome://extension.

Could someone advise me on how to retrieve the hostname in offers.js? Is there a way to append data to offers.html from myscripts.js? And where should I call the API and how can I add the result to the body of the iframe?

Answer №1

Is there a way to retrieve the host name in offers.js or possibly add data from myscripts.js to offers.html?

If you simply need the URL, consider passing it as a query parameter like this:

// myscript.js
var url = chrome.extension.getURL('offers.html?url=' + window.location.host);

// offers.js
// Utilizing https://developer.mozilla.org/en-US/docs/Web/API/URL
var host = new URL(location.href).searchParams.get('url');

If you require extracting additional information from the page, you can use postMessage for communication with the embedded window.

// myscript.js
iframe.contentWindow.postMessage(message, chrome.runtime.getURL(""));

// offers.js
window.addEventListener("message", function(event) {
  var message = event.data;
  /* ... */
});

This communication can also be two-way, although that goes beyond the initial question's scope.

Where should I make the API call and how do I insert the result into the iframe body?

You should make the API call in offers.js and then manipulate the DOM of that page accordingly.

Edit: Unfortunately, security policies from the page may interfere with making an HTTP call within the iframe, causing potential issues.

  • It is recommended to always use HTTPS for better user privacy protection.

  • To work around this restriction, consider delegating the API call to a background page using Messaging, as background pages are not affected by this limitation.

  • Remember, sticking to HTTPS is crucial as failure to do so could lead to rejection when your extension undergoes review.

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

Incorporating script within an ASPX webpage

I've been struggling with using this code on an ASPX page. I keep trying to implement it within a text box on the same page, but without success. Strangely though, I can successfully use the script within a text box in my master page. Any assistance w ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

It appears that using "object[prop]" as a name attribute does not function properly in HTML

After using console.log on the req.body I received this output: [Object: null prototype] { 'shoe[name]': 'Shoe Name', 'shoe[description]': '', 'shoe[pictures]': '', 'shoe[collections] ...

Having trouble extracting the responseText from the Ajax request

My current challenge involves making an ajax call and receiving an Object in the response. However, when I attempt to access "responseText," it keeps returning as undefined: var results = API.get('users', { username: un, userpass: pw } ); conso ...

How can I implement a hover effect without triggering a click event?

My structure is pretty basic, here it is: .container { height: 100vh; width: 100%; pointer-events: none; } .click-layer { background-color: #ccc; position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: auto; } .box { ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...

How can I create a clickable <div> element containing multiple links and trigger only one action?

Within my code, there is a <div> element that has been made clickable. Upon clicking this <div>, the height and text expand using the jQuery function $(div).animate();. While this functionality works as intended, I am encountering a slight issu ...

Utilizing jQuery to attach events to dynamically generated elements

I have a scenario where I am uploading multiple images and inserting them into specific div elements. These divs should toggle a class when clicked. Should I include the part of code that adds the onclick event inside the ajax success function? Your help i ...

Why isn't the array loading upon the initial click in AngularJS?

// CONFIGURING SERVICES app.service("PictureService", function($http) { var Service = {}; Service.pictureLinkList = []; // RETRIEVING PICTURE LINKS FOR THE PAGE $http.get("data/img_location.json") .success(function(data) { Service.pictureLinkLi ...

"Is there a way to retrieve the file size from a source on a different site

Hey everyone, I'm pulling src's from another website and have them in an array like ["www.another.com/pic1.png", "www.another2.com/pic2.jpg"]. I tried using XMLHttpRequest and checking the file.size, but CORS restrictions are preventing me from ...

Navigating through elements within underscore.js templates

Can someone please help me out? I'm finding this task more difficult than it should be, so I must be overlooking something simple... I am working with a variable that is acting as an underscore template. Here is an example of the code snippet: var t ...

What is the proper way to connect my JavaScript code to my HTML form?

My JavaScript function is not working properly when I try to submit a form on my website. <form onsubmit="validateRegistration()"> <p> // Email registration <input type="text" id="e-mail" placeholder="Email" /> </p> ...

Changing a file object into an image object in AngularJS

Can a file object be converted to an image object? I am in need of the width and height from the file (which is an image). Here is my code: view: <button id="image_file" class="md-button md-raised md-primary" type="file" ngf-select="uploadFile($file ...

Identical HTML elements appearing across multiple DOM pages

My question might seem silly, but I'm facing an issue. I have several HTML pages such as index.html and rooms.html, along with a main.js file containing scripts for all of these pages. The problem arises because I have variables like const HTMLelemen ...

The Print Preview Displays No Content When an External Stylesheet Reference is Included in the Printable HTML Content

Is there a way to print the contents of a DIV on a webpage? Currently, I am using JavaScript to retrieve the contents of the div and then passing it to a new window object where I call the .print() function. The text contents and images are displayed corre ...

Puppeteer exhibiting unexpected behavior compared to the Developer Console

My goal is to extract the title of the page using Puppeteer from the following URL: Here's the code snippet I am working with: (async () => { const browser = await puppet.launch({ headless: true }); const page = a ...

I rely on Grunt to manage my Angular 1 app, along with grunt-connect to host the website. However, when I refresh the page, there is no fallback mechanism in place, resulting in a 404 error and

Currently, I am utilizing Grunt to manage my angular 1 application and grunt-connect to serve the website. However, I have encountered an issue where on refresh, there is no fallback mechanism in place which results in a 404 error and a blank white screen. ...

Managing unanticipated errors in Express while utilizing async/await mechanics

Consider this TypeScript code snippet: app.get('/test_feature', function (req: Request, res: Response) { throw new Error("This is the bug"); }); app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFun ...

Are mutations in Vuex guaranteed to be atomic?

I'm currently investigating the atomicity of mutations in Vuex. The code snippet I'm reviewing has me questioning whether the CHANGE_A mutation could potentially be triggered while CHANGE_B is still in progress: const mutations = { [CHANGE_A]( ...