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

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

Utilizing Smart Table for Data Binding with JSON Dataset

I need help binding a JSON file to a smart table. How can I use the loop function for iteration? The design of the smart table is displaying, but the data from the JSON file is not binding. Here is the JSON file: [ { "year": 2013, "id ...

Menu icon in Next.js/React/Tailwind not triggering close action when clicked again, causing responsiveness issue

Hey there, I'm relatively new to working with Next.js and React. Right now, I'm tackling the challenge of creating a responsive navbar that toggles open and closed when clicking on the hamburger icon (and should also close when clicked outside th ...

Creating a React component that can dynamically render either an image or a video based on the incoming API data is a great way to

I'm currently immersing myself in learning and honing my skills in React. My goal is to develop a React web application that enables users to view and scroll through Nasa's picture of the day based on their selected date. The API I will be utili ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

Npm is unable to locate the package.json file in the incorrect directory

Hello, I am currently in the process of setting up webpack. I have all the configurations ready, but when I attempt to execute webpack in my terminal, it looks for the package.json file in the incorrect location. Is there a way for me to modify the path ...

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

sticky bootstrap datepicker anchored to the top of the screen

Currently, I am working on a form that includes a date picker using the bootstrap datepicker In this setup, I have hidden the main bootstrap field and added three custom fields. When any of these fields are clicked, the calendar should open next to them. ...

Automatically generated VueJS function

Creating a logging system for my Javascript Project using VueJS and Vuex To make logging methods accessible to all components, I am utilizing a global Mixin : import { mapState, mapActions } from 'vuex' import LogLevel from '@/enums/logger ...

Managing various swipe interactions using HTML and JavaScript/jQuery

I'm in the process of creating a mobile multiplayer game using HTML5 and Javascript. The jQuery Plugin "touchwipe" is utilized to manage swipe events in various divs like this: $('#play1').touchwipe({ wipeLeft: function(){ if ...

Auto play feature malfunctioning in Onsen-UI Carousel attribute settings

When utilizing onsen UI in my mobile web application, I encountered an issue with the autoplay property not functioning properly within the carousel. <ons-page> <ons-toolbar> <div class="left"> <ons-toolbar-button on ...

Having trouble with the Wordpress JS CSS combination not functioning properly and unable to determine the cause

I recently set up a page on my WordPress site using the Twenty Seventeen theme. At the top of the page, I created a toolbar for users to easily adjust the font size and background color. Check out the image below for reference: See Image for Bar Here&apo ...

Navigating Error: net::ERR_CONNECTION while utilizing Puppeteer

I attempted to utilize a proxy from the following site: Below is my Puppeteer scraping code (deployed on Heroku), encountering an error at the .goto() method, as mentioned in the title: const preparePageForTests = async (page) => { const userAgent = & ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

Issue with two Jquery slider forms

Within a Jquery slider, I have implemented two distinct forms (using this specific Jquery slider: http://tympanus.net/Tutorials/FancySlidingForm/) . My goal now is to establish JavaScript/jQuery validation for these two forms separately BASED on the form ...

Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being ...

Exploring the World of Browserify Submodules

/xyz /abc.js /abcdef.js /index.js When working with node.js, if you use the require statement for a directory (require('xyz')), it will automatically search for an index.js file within that directory and return the exports defined in that ...

How to create expandable nodes with lazy-loaded children in Dynatree?

I have successfully implemented a tree navigation menu using Dynatree (). The tree consists of four levels: company, group, user, and computer. Each object within the tree is selectable, opening a page displaying the properties of that specific object. How ...