Engaging with the crossrider sidepanel extension

When it comes to the crossrider sidepanel, I prefer using an iframe over js-injected html to avoid interference with the rest of the page. However, I am struggling to establish any interaction between my browser extension and the iframe.

I believe adding a sidepanel with an extension is pointless unless there can be some basic JS communication involved. My goal is to incorporate options like checkboxes in the iframe that can control the extension. Since the plugin exists, I assume there must be a way to achieve this.

My ideal scenario would involve handling basic input in the child iframe and sending save/load commands back to the extension. Is message passing the answer here? And if so, which API should I use for this purpose?

I found a related query on Stack Overflow: Accessing iframe from chrome extension

[EDIT]
After trying out a few approaches...

  1. It appears that the expected practice is to host the iframe's HTML content externally. This seems odd as it should ideally be available locally within the extension. Hosting externally becomes inconvenient when you need to view pages offline. I find this unnecessary and have decided to disregard it as an option.

  2. Another method I tested was providing the HTML directly for the sidebar without placing it inside an iframe. I personally prefer iframes because they keep CSS and JS separate, minimizing interference between the page and the extension.

    So, I attempted creating an iframe through the `html` sidebar attribute with an ID, and injected the content after a 100ms delay using `myiframe.contentWindow.document.open/writeln/close()`. While this works well in Chrome, it fails in Firefox due to a security error (`The operation is insecure` on `open()`).

  3. A different approach involves providing the iframe content through the `src` URL (for sidebar, I used a data address for the `url` attribute): Html code as IFRAME source rather than a URL. While this method worked in Firefox, it triggered a CORS error in Chrome stating `The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.` as well as `Warning: Blocked a frame with origin "http://localhost" from accessing a cross-origin frame. Function-name: appAPI.message.addListener`.

These CORS issues seem illogical to me. It's all originating from my code within the same extension, injected into the same page. There shouldn't be any cross-origin problems since I created it all. If I have the authority to modify the origin, then worrying about security measures feels redundant.

Answer №1

When utilizing the url sidebar property to load HTML content in your sidebar (such as a hosted webpage), you can take advantage of the extension's Run in Iframe functionality for seamless communication between the iframe extension and the parent window's extension.

To implement this, enable the extension to run in iframes (Settings > Run in Iframes) and then utilize the extension.js to handle loading the sidebar and managing messaging. Below is an example code snippet that loads a webpage containing a button with the ID btnSave:

Hosted webpage code:

<html>
<head>
</head>
<body>
  <div id="mySidebar">
    My sidebar content
    <br />
    <button id="btnSave">Save</button>
  </div>
</body>
</html>

extension.js code:

appAPI.ready(function($) {
  // Verify if running in iframe and the sidebar page is loaded
  if (appAPI.dom.isIframe() && $('#mySidebar').length) {
    // Set click handler for the button to send message to the parent window
    $('#btnSave').click(function() {
      appAPI.message.toCurrentTabWindow({
        type:'save',
        data:'My save data'
      });
    });
    // Exiting iframe code...
    return;
  }

  // Parent window message listener
  appAPI.message.addListener(function(msg) {
    if (msg.type === 'save') {
      console.log('Extension:: Parent received data: ' +
        appAPI.JSON.stringify(msg.data));
    }
  });

  // Create the sidebar
  var sidebar = new appAPI.sidebar({
    position:'right',
    url: 'http://yourdomain.com/sidebar_page.html',
     title:{
      content:'Sidebar Title',
      close:true
    },
    opacity:1.0,
    width:'300px',
    height:'650px',
    preloader:true,
    sticky:true,
    slide:150,
    openAction:['click', 'mouseover'],
    closeAction:'click',
    theme:'default',
    scrollbars:false,
    openOnInstall:true,
    events:{
      onShow:function () {
        console.log("Extension:: Show sidebar event triggered");
      },
      onHide:function () {
        console.log("Extension:: Hide sidebar event triggered");
      }
    }
  });
});

However, if you are using the html sidebar property to load your sidebar's HTML, this solution may not be suitable since the extension does not operate in this scenario. You could explore alternative methods suggested in the StackOverflow thread cited to communicate with the parent window (dependent on the browser) which, in turn, can interact with the extension through our CrossriderAPI event.

[Disclaimer: I am a Crossrider employee]

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

What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to h ...

What is the best way to store and retrieve data from the current webpage using HTML, CSS, and JavaScript?

Is there a way to persistently save the button created by the user even when the browser is refreshed? Here is an example code snippet: function create(){ const a = document.createElement("button") document.body.appendChild(a) const b = documen ...

Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specif ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

Implementing a language switch feature for text display in Node.js and Next.js websites

One of the features my client is requesting for a web app is dual language support, where users can easily switch between French and English. To address this requirement, I incorporated a button that toggles a state and saves the user's language pref ...

Convert h264 video to GIF using Node.js

Currently, I'm utilizing the "pi-camera" library to successfully record video in a raw h264 format on my Raspberry Pi. However, I am encountering an issue with the node.js library "gifify" which keeps throwing the error "RangeError: Maximum call stack ...

The persistent connection of Socket.io results in consecutive connections while disregarding other occurring events

My goal is to create a unique web application where users can engage in toroidal chess matches with one another. This is the code from my app.js file on the server side: var express = require('express'); var app = express(); var http = require(& ...

Clearing Input Values in Text Boxes, Dropdowns, and Checkboxes in ASP.NET MVC

Currently, I am working with Asp.net MVC 4 using C#. On one of my pages, I have a Text box, Drop down, and checkbox all together as search filters. There is also a "Clear" button to reset the values. When this button is clicked, I want the textbox value to ...

Converting an object of objects into an associative array using Javascript and JSON

Using AngularJS, I am sending this data to my API : $http.post('/api/test', { credits: { value:"100", action:"test" } }); Upon receiving the data in my nodeJS (+Express) backend, it appears as follows : https://i.stack.imgur.com/NurHp.png Why ...

Resolving Route Problems in Node.js with Express

Currently, I am in the process of developing a website using Express and NodeJS. One issue that I have encountered is related to routing. In my app.js file, I have defined a route that expects a parameter like so: app.get(['/purchase/:purchaseID&apos ...

Utilize JSON categories to assign groups to TextFields or Selects according to a JSON data attribute

I have retrieved multiple JSON groups from an API, each containing one or more questions objects. My goal is to display each question along with its corresponding response in a MUI TextField or Select component, based on the value of QuestionType. Current ...

What is the best way to determine if two external values are equal within a mongodb criteria object?

Consider the following collection: {id: 1, name:"abc"}, {id: 2, name:null} When testing a property, I typically use this method: db.collecton.find({name:"abc"}, {name:1}); // This will return the first document. Now, I want to incorporate two external ...

Error: The JSONP request encountered an unexpected token, causing a SyntaxError

Asking for data using AJAX: $.getJSON('https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD&callback=?', function(result) { console.log(result); }); Encountering an error: "Uncaught SyntaxError: Unexpected token :" ...

Is there a way to convert Firebase JSON into a JavaScript object? If so, what is the method to

I am currently working on using the kimono web scraper in conjunction with Firebase to obtain data stored as JSON. To convert the JSON to XML, I am utilizing a JavaScript library which allows me to create a variable from the JSON file (an example is shown ...

Is it possible to use export default Enum in TypeScript?

I am facing an issue with exporting an enum object as default at the top level in my code. Here is what I tried: export default enum Hashes{ FOO = 'foo', BAR = 'bar', } However, this resulted in an error message: Module parse failed ...

Engage with React JS arrays of objects

I have a specific object structure that looks like the following: [ { "periodname": "Test", "periodtime": "" }, { "periodname": "", "periodtime&quo ...

Retrieve an Excel file using Selenium through a URL, but only obtain JavaScript code instead

I am attempting to download an Excel file using its URL, but all I receive is JavaScript code. I'm unsure of how to retrieve the actual file instead of just the JS code. Here is my current code: # -*- coding: utf-8 -*- from selenium import webdrive ...

JavaScript for loop similar to Python'sIn JavaScript, the

As someone who is new to programming, I primarily use Python but have now encountered a situation where I need to work with JavaScript for a project utilizing Phonegap. The query retrieved from the server looks like this: [["CompanyName", "lat", "long", ...

Error: Attempting to assign value to the 'innerHTML' property of null in a Wordle clone with local storage

While developing a Wordle-inspired game for my website, I decided to utilize Local Storage to store the user's progress. Everything seemed to be working smoothly until an unexpected error occurred: "Uncaught TypeError: Cannot set properties of null (s ...

Incorporating a for loop, ExpressJS and Mongoose repeatedly utilize the create method to generate

When users input tags separated by commas on my website, ExpressJS is supposed to search for those tags and create objects if they don't already exist. Currently, I am using a for loop to iterate through an array of tags, but only one object is being ...