execute the execCommand function following an ajax request

I am currently developing a WYSIWYG editor and encountering an issue with image handling using execCommand. Here is a simplified example of my page structure:

<div id="buttons_panel"><input id="img_submit" type="button"/></div>

<div id="img_handle" style="display:none;">
<div id="ajax_upload"></div> <!-- AJAX IMG UPLOAD FROM -->
<div id="images"></div> <!-- DIV FOR ALL UPLOADED IMAGES DISPLAY -->
</div>

<iframe id="text_content"></iframe>

The JavaScript I am using, in a nutshell, involves showing the hidden div to upload an image via ajax and display all uploaded images:

<script>
$("#img_submit").click(function(){
$("#img_handle").show();

/* HANDLE IMG UPLOAD WITH AJAX AND RELOAD ALL IMAGES INTO #images DIV */
});
</script>

Everything works fine - once a new image is uploaded via ajax, it is appended to the images div like this:

function loadImgs(){
var loadImages="PATH/TO/URL"; 
$.post(loadImages, {request:"loadImages"}, function(response){
$("#images").append(response);
insert_img();
});
}

Subsequently, upon clicking on any of the results, the following function is triggered:

function insert_img(){$(".img_insert").click(function(){
var frame = document.getElementById('text_content'); frame.document.execCommand('InsertImage',false,"../PATH/TO/IMG"); 
});}

However, I encounter an issue where the execCommand fails to work - Firebug displays:

"getElementById("text_content").document UNDEFINED"

All other execCommand functions (e.g., italic, bold, font-color) work as intended on the page except for this specific case. Can someone please assist me in finding a solution?

Answer №1

To access the document object within an <iframe>, it is recommended to use the contentDocument property rather than simply document. While this method may not work in older browsers, you can fallback to using contentWindow.document instead.

The code provided below should function correctly in most modern browsers, excluding those that do not support contentDocument or contentWindow:

function getIframeDocument(iframeEl) {
    return iframeEl.contentDocument || iframeEl.contentWindow.document;
}

function insert_img(){
    $(".img_insert").click(function() {
        var frame = document.getElementById('text_content');
        getIframeDocument(frame).execCommand('InsertImage',false,"../PATH/TO/IMG");
    });
}

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

effortlessly eliminate the Google MyMap watermark from an iframe using ReactJS

I am new to ReactJS and I would like help on how to hide the watermark on a Google My Map. Can someone please assist me with this? <iframe src="https://www.google.com/maps/d/u/1/embed?mid=1OMSkPKZi-U-CnmBr71zByNxp8HYi-vOc&ehbc=2E312F" fram ...

Looking for a way to implement an AJAX push feature?

I'm currently working on a web application that requires data to be updated whenever changes occur. Right now, I have set up an interval of 5 seconds to fetch data from the server using ajax requests. The issue I am facing is that unnecessary calls ...

Why is access to fetch from the origin localhost blocked by CORS policy, while posting using ajax does not face this issue?

Let's dive into the difference between AJAX and Fetch without involving CORS. I want to understand why an AJAX POST request works flawlessly while a Fetch POST request fails! Currently, I am using jQuery and AJAX for both GET and POST operations. Whe ...

Is it possible for me to trigger a custom event using an eventBus listener?

In the Vue component, I have the following setup: data: function() { return { quotes: [] }; }, created() { eventBus.$on("quoteWasAdded", message => { this.quotes.push(message); this.$emit("quotesWereUpdated", this.quot ...

Is the HTTP request from the browser being recorded?

When sending an HTTP request using fetch to website A from the Chrome console on website B, is it possible for website B to track any information about that request, or is it strictly client-side? In other words, can website B detect this action? Thank yo ...

Guide to setting up sub-routes in fastify

Currently, I am incorporating fastify as the web framework for my nodejs project. My aim is to organize and call all routes from a specific directory while having a base route established in the main JS file, similar to how it's done in express. Despi ...

Send function arguments to populate dropdown menus with JSON data

Is there a way to pass the parameter into "foodName" from the function that sends the url and id, without explicitly mentioning it in the function? For example, could you create a more generic function like: call('/url/to/foodlist', "foodLis ...

Problem with HTML relative paths when linking script sources

Having trouble with a website I constructed using Angular. The problem lies in the references to javascript files in index.html. The issue is that the paths in the HTML are relative to the file, but the browser is searching for the files in the root direct ...

Retrieve isolated scope of directive from transcluded content

I am not certain if it is possible, but I am essentially looking for a reverse version of the '&' isolate scope in AngularJS. You can check out this Plunkr to see an example. In essence, I have created a custom directive that provides some r ...

What is the optimal order for executing JavaScript, jQuery, CSS, and other controls to render an HTML page efficiently?

What are some recommended strategies for optimizing webpage loading speed? What key factors should be taken into consideration? ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

The div element is not adjusting its size according to the content it

Essentially, I want the #main-content div to expand so that its content fits inside without overlapping, as shown in the codepen example. I've been unsuccessful in implementing the clearfix or overflow:hidden solutions so far. It's puzzling why ...

Guide on leveraging npm start to compile ES6 React components and Foundation Sass

Following a tutorial on setting up a React project, everything seemed to be working perfectly after installation. However, I now need to incorporate Foundation as the front-end library for a website. The issue arises because the tutorial's server.js ...

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

Dynamic sizing of HTML elements

I'm currently developing a timeline feature using slick slider and I'm exploring ways to dynamically adjust the vertical line height for each event based on the text content. You can view the current timeline implementation at the following link ...

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

Dealing with browser file retrieval utilizing ajax and a spring controller

I am currently facing an issue in my project that involves passing parameters from an AJAX POST request to a Spring controller. The controller then sends these parameters to a Java service which generates a file on the server and returns the file path back ...

Is there a different alternative to @JavascriptInterface in Android WebView?

I understand how to invoke a Java method within JavaScript code using the @JavascriptInterface annotation. However, I am facing an issue when trying to determine which JS method should be called from Android. Currently, I am triggering an Android Dialog ...

"Optimizing Performance: Discovering Effective Data Caching

As a developer, I have created two functions - one called Get to fetch data by id from the database and cache it, and another called POST to update data in the database. However, I am facing an issue where I need to cache after both the get and update oper ...