Monitor the content script for any updates in the AJAX response that alter the value of the textarea

I am currently developing a WebExtension for a text editor that utilizes an ajax request to format the text when a button is clicked. I need the addon to detect any changes in the textarea element.

Despite attempting to use onchange or oninput events, they do not seem to trigger after receiving the response from the ajax request. The function responsible for setting the body upon ajax response is as follows:

function setBody(text) {
  $(opts.codeEl).val(text); // opts.codeEl refers to the specific textarea
}

The ajax response data structure is like this:

{"Body":"Hello World","Error":""}

Is it feasible to manage this ajax request/response scenario within a WebExtension Content Script? Is there a way to monitor changes in the textarea's value in the DOM and potentially intercept the response?

The ajax request is handled in the website's separated javascript code and is isolated from my content script which controls the text editor through the WebExtension. Here is how the request is formulated:

function fmt() {
  loading();
  var data = {"body": body()};
  if ($(opts.fmtImportEl).is(":checked")) {
    data["imports"] = "true";
  }
  $.ajax("/fmt", {
    data: data,
    type: "POST",
    dataType: "json",
    success: function(data) {
      if (data.Error) {
        setError(data.Error);
      } else {
        setBody(data.Body);
        setError("");
      }
    }
  });
}

Edit

Integrating an ajaxComplete handler:

$(document).ajaxComplete(function(event, jqxhr, options) {
    if(options.url === "/fmt") {
      console.log("formatted");
      $('#code').change();
    }
});

Embedding this script into the target site's header will execute upon receiving the ajax response. However, any attempts to alter the DOM using injected scripts such as change() or onchange() result in a security error stating "Permission denied to access property 'apply'."

Answer №1

Using jQuery's .val(value) method does trigger the change event. You can either call .change() or .trigger("change").

If you are uncertain about when the function setBody will be called, you can utilize .ajaxStop() to automatically call .change() on $(opts.codeEl) once the last $.ajax() call is completed.

$(function() {

  let opts = {
    codeEl: document.querySelector("textarea")
  }

  $(opts.codeEl).on("change", function(event) {
    console.log("changed")
  });

  function setBody(text) {
    $(opts.codeEl).val(text)
  }

  let url = URL.createObjectURL(
    new Blob([
      JSON.stringify({
        "Body": "Hello World",
        "Error": ""
      })
    ], {
      type: "application/json"
    })
  );

  $.get(url)
  .then(function(data) {
    URL.revokeObjectURL(url);
    setBody(JSON.stringify(data))
  });
  
  $(document).ajaxComplete(function(event, jqxhr, options) {
    if (options.url === url) {
      console.log("ajaxStop");
      $(opts.codeEl).change(); // trigger `change` event
    }
    
  });

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<textarea></textarea>

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

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Tips for transforming my JSON format into the necessary column layout for C3.js

The data structure returned by my API is as follows. However, I need to reformat this structure for use in C3.js. { "data":{ "test7":[ { "Date":"2016-04-26 00:00:00", "aId":7, "Amount":436464, "Piece":37 ...

Issue with Node.js: Modifications to route settings are not reflected

It's puzzling - the changes I make to my route settings in the MEAN environment, with Node v0.12.2 and express 4, don't seem to have any effect! Specifically, when I use ".sendfile()" to respond to client requests. app.get('/', functio ...

When using $http in AngularJS, an error may occur when it

I ran a test on my PHP code independently and obtained the following output: {"tabId":1,"tabName":"Main","uId":"1"}{"tabId":2,"tabName":"Photography","uId":"1"} However, my AngularJS application is unable to receive the callback and is throwing an error ...

The NodeJs backend is not being recognized by the React app

Having trouble integrating a Node.js backend with my React JS app initialized with Vite. When I add the index.js file and run the command, only the React part initializes and does not recognize posts and express routes. Can anyone assist? Here are my App.j ...

Acquire information from a website utilizing an ajax function with VBA in Excel

I'm looking to scrape information from and transfer it into an Excel sheet. The challenge I'm facing is that the webpage utilizes an ajax function and does not have individual elements for each entry. Here's a snippet of the HTML code in qu ...

Creating custom themes in React Native using dynamically loaded JSON data

Is it possible in React Native to override custom styles with dynamically fetched font-size and background color values from a server's JSON data? I am looking to incorporate this JSON data theme into my style themes. Can you provide the syntax for cr ...

Javascript will not recognize or interpret PHP's HTML tags

When PHP sends HTML strings to HTML through AJAX wrapped in <p class="select"></p> tags, the CSS reads the class perfectly. However, JavaScript/jQuery does not seem to work as expected. Even when trying to parse <p onclick="function()">&l ...

Is Mongodb making an asynchronous request?

How can I ensure synchronous execution of code in this scenario? Despite trying various methods, the issue persists where res.render is called too early and certain objects from state are missing. The playingCollection refers to a MongoDB collection. va ...

Looking to retrieve a specific data element within Vue.js?

Here's a thought-provoking query for you. Imagine I have some data stored in an element in the form of an array like this: data: { product: socks, variants: [ { variantId: 2234, variantColor: 'Green', varian ...

Determine in JavaScript whether an array includes a function in its elements

Currently, I am adding anonymous functions to an array in the following manner: myArray.push(function(){ /* some unique code here */}); myArray.push(function(){ /* even more unique code here */}); Afterwards, I execute all the functions by doing while ( ...

Show several fresh windows

Greetings everyone. Let me explain my current situation: I have a search page where users can select a product from a drop-down list, and upon clicking a button, a gridview is displayed showing the specifications of the selected product. What I'm a ...

What is the extent of an object within a JavaScript Array?

Exploring scopes in JavaScript has led me to an interesting discovery when calling functions from an array. In the example below, I experiment with three different scopes: one bound to an Object named foobar, one bound to window, and a third one which po ...

Need assistance with passing a model and a string in MVC5?

Below is the code snippet I am working with: JavaScript: $(document).ready(function () { //Thing is model var things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red&a ...

The PHP script outputs the symbol 'a' just before encountering the opening curly brace '{' in the JSON data

Here is the PHP function I have: function _return($message, $status=200) { $return = json_encode([ "message" => strval($message), "status" => intval($status) ], JSON_UNESCAPED_UNICODE); echo($return); exit(); } After ...

Why is it displaying undefined even though there is data stored in Firebase?

I am experiencing an issue where the datatable row is displaying "undefined" instead of the data from my Firebase database. Even when I tried inserting random data into the HTML file for the datatable, it still shows undefined. Here is a link to My Datata ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

An unexpected key was found in the create store function in React Redux

Encountering the issue An unexpected key "characters" was found in the initialState argument passed to createStore. Expected keys are: "marvelReducer", "routing". Any unexpected keys will be disregarded. rootReducer : import { combineReducers } from &a ...

What is the solution to the error "Maximum update depth exceeded. Calls to setState inside componentWillUpdate or componentDidUpdate" in React?

Everything was running smoothly until this unexpected issue appeared. I attempted to change the condition to componentDidMount, but unfortunately, that didn't resolve the problem. The error is occurring in this particular function. componentDidUpd ...

Challenges with pjax/ajax and handling the browser's back button

I've implemented pjax to ajaxify my menu links, which works well until I encounter an issue with the browser back button. In my JavaScript file, I have both Common Script files (to load all necessary js files when the user hits the URL) and Script fil ...