ExecCommand modify width and height in insertImage

1

Good afternoon. I think I started in this forum with my left foot, so I try again. If I do not understand now, I will not bother anymore.

As Travv indicated, I reformulate my question:

When I use execCommand insertImage, I would like the image inserted in a text field to have other measures in pixels, for example if the original image is 200 x 200 px, it is possible to send the URL of the image to the insertImage command and other measures? (for example, 100 x 100 px).

I tried the following:

var img; 
if(!(img=prompt('ingresar url','http://')))return; 
img.width=100+'px';
img.height=80+'px';
document.execCommand('InsertImage',false,img);

But although I do not get an error, it does not alter the image either.

I await your answers, thank you very much.

    
asked by Rubén 26.01.2018 в 19:51
source

1 answer

0

The problem of using insertImage is that it does not return an image controller and selecting it once it is created is not easy, which complicates the task of resizing.

To be able to find the image and change the size, you could choose several options, but they all have some kind of problem:

  • You could use insertHTML instead of insertImage . You would create a string that contains the code of an image in HTML with the src that you just read and the size you want ... the problem is that then the code would be vulnerable to XSS attacks ( insertImage has some measures of security that you would have to jump to create the HTML of img ).
  • You could use insertImage and then select the image from the source that was provided. This would be simple and you would not have security problems like the one indicated above, but if another image with the same URL already exists, it could be a problem because you would not know which of them would be selected.
  • You could use insertImage and take advantage of the cursor being placed just after the inserted image to select the previous node (although this behavior is not assured). This would ensure that the image that was just inserted is selected, but it is more complex to develop than the other options.
  • So it would be with method # 2:

    function crearImagen() {
      var img;
      if (!(img = prompt('ingresar url', 'https://placehold.it/200x160'))) return;
      // creamos la imagen con el src indicado
      document.execCommand("insertImage", false, img);
      
      // seleccionamos la imagen que tenga ese src y cambiamos el tamaño
      var imagen = document.querySelector("img[src='" + img + "']");
      imagen.style.width = "100px";
      imagen.style.height = "80px";
    }
    div { 
      border: 1px solid #ccc; 
      margin: 10px;
      padding: 10px;
    }
    <button onclick="crearImagen()">Crear Imagen</button>
    
    <div contenteditable>
      Pulsa en el div y luego en el botón "Crear Imagen".
    </div>
        
    answered by 27.01.2018 в 03:43