Stopping a Firefox addon with a button click: A step-by-step guide

Utilizing both the selection API and clipboard API, I have implemented a feature in my addon where data selected by the user is copied to the clipboard directly when a button is clicked (triggering the handleClick function). However, an issue arises when attempting to stop the addon by clicking back on the button, resulting in an error message stating that data should be string.

var self = require('sdk/self');
var clipboard = require("sdk/clipboard");
var selection = require("sdk/selection");
var selected_text =[];
var result;
var flag = false ;
function myListener() {

    if (selection.text){
        selected_text= selected_text.concat(selection.text);
        result= selected_text.toString();
    }  
    clipboard.set(result);

}
function handleClick(state) {
        if (!flag){
            selection.on('select', myListener);
            flag= true;
        } else {
            clipboard.set(null);
        }
}
require("sdk/ui/button/action").ActionButton({
    id: "Selection",
    label: "Click to start saving your next selections to clipboard",
    icon: {
        "16": "./icon-16.png",
        "32": "./icon-32.png",
        "64": "./icon-64.png"
    },
    onClick: handleClick
});

Exact error Msg :

JPM undefined   Message: RequirementError: The option "data" must be one of the following types: string

If anyone could provide guidance on how to successfully stop and start the addon with a button click and identify where the error is occurring, it would be greatly appreciated.

Answer №1

On Firefox Nightly or with e10s enabled, the selection API may not work properly. Even though the event is emitted for text boxes, no selection is actually detected. This results in selection.text being null, which is not a valid value for the clipboard API.

If using Firefox release without e10s enabled, the code should function correctly.

Edit

Remember that passing null to the clipboard API will raise an exception. Instead, consider something like:

const clipboard = require("sdk/clipboard");
const selection = require("sdk/selection");

function onSelect() {
  if (selection.text) {
    clipboard.set(selection.text);
  }
}

require("sdk/ui/button/toggle").ToggleButton({
    id: "Selection",
    label: "Click to start saving your selections to clipboard",
    icon: {
        "16": "./icon-16.png",
        "32": "./icon-32.png",
        "64": "./icon-64.png"
    },
    onChange(state) {
      if (state.checked) {
        selection.on("select", onSelect);
      } else {
        selection.off("select", onSelect);
      }
    }
});

I've simplified the logic for clarity, but feel free to customize it as needed for your specific use case.

If you wish to clear the clipboard, consider setting it to an empty string when removing the listener. However, this may affect the overall functionality of the code.

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

Has the user successfully authenticated with Google?

Possible Repetition: How to verify if a user is logged into their Google account using API? I'm working on a website that displays a Google Calendar. My query is: Can I determine whether a user is currently logged into a Google Account? If it&ap ...

How to customize TextField error color in Material-UI using conditional logic in React

Currently, I am incorporating the React Material-UI library into my project and faced with a challenge of conditionally changing the error color of a TextField. My goal is to alter the color of the helper text, border, text, and required marker to yellow ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Is it possible for me to utilize this code for logging in through a dialog box?

Here is the code snippet I have on the client side: <p>Username:</p> <p><asp:TextBox ID="tbUsername" runat="server"></asp:TextBox></p> <p>Password:</p> <p><asp:TextBox ID="tbPassword" runat="server ...

Updating a marker in real-time using API response

I'm trying to create a simple web application that allows users to enter a city name in an input box, which then triggers the updateMap function to geolocate and map the city with a marker. After mapping the city, another function called updateTemp is ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

Can someone help me figure out this lengthy React error coming from Material UI?

Issues encountered:X ERROR in ./src/Pages/Crypto_transactions.js 184:35-43 The export 'default' (imported as 'DataGrid') could not be found in '@material-ui/data-grid' (potential exports include: DATA_GRID_PROPTYPES, DEFAULT ...

The Node.js promise failure can be unpredictable, despite being properly managed

In my journey to master MongoDB, I am currently exploring its capabilities by building a basic blog application. However, I have encountered an issue with the code responsible for saving blog posts - it seems to be inconsistent in its success rate, sometim ...

The 'id' property cannot be accessed because the data has not been retrieved successfully

After loading my App, the data from Firebase is fetched in componentDidMount. I am currently passing postComments={comments} as a prop. However, before this happens, my app crashes with Cannot read property 'id' of undefined on line const c ...

The JSON data fails to load upon the initial page load

I am having trouble getting JSON data to display in JavaScript. Currently, the data only shows up after I refresh the page. Below is the code I am using: $(document).ready(function () { $.ajax({ url:"http://192.168.0.105/stratagic-json/pr ...

Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popu ...

jquery ajax function that returns an object when successful

Below is a brief example of an AJAX call wrapped in a function. MyNS.GetStrings = function (successCallback, errorCallback) { var url = serverUrl + "/GetStrings"; $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", dataType: ...

Error in Node-Fetch Mapping: Unable to access property 'map' of an undefined entity

Encountering an issue with the "map" section when attempting to run it - receiving an error message stating "Cannot read property 'map' of undefined" The customers constant is defined above, so I'm unsure where the undefined value is origin ...

Optimal method for transforming the values of an object or array in JavaScript

I have a group of values that need to be transformed into new values using a legend. The process might sound confusing at first, but it will become clear shortly. To achieve this, I've relied on associative arrays or objects in JavaScript to serve as ...

Is there a way to retrieve the current map center coordinates using the getCenter function in @react-google-maps/api?

I am currently working with the GoogleMap component provided by @react-google-maps/api, but I am struggling to figure out how to obtain the latitude and longitude coordinates of the map's center after it has been moved. After some research, I came ac ...

How can I match all routes in Express except for '/'?

I've been working on implementing an authentication system for my app that involves checking cookies. My approach was to use router.all('*') to handle every request, verify the cookie, and then proceed to the actual handler. However, I encou ...

Incorporate a variable into a string

My task here is to prepend a variable before each specific string in the given text. For example: var exampleString = "blabla:test abcde 123test:123"; var formattedString = "el.blabla:test abcde el.123test:123"; In this case, whenever there is a pattern ...

Unexpected behavior encountered when running Angular 8 radio button checked function

I have an Angular 8 web app with some unique logic implemented as shown below: HTML: <div *ngFor="let item of selectedItems;"> <input type="radio" [(ngModel)]="mySelectedItem" [value]="item.key" (ngModelChange)="setCh ...

Update the image and heading simultaneously when hovering over the parent div

I am looking to enhance the user experience on my website by changing the color of headings and images when a user hovers over a specific section. Currently, I have been able to achieve this effect individually for each element but not simultaneously. Any ...