How to replace all images src from paste slice object?

I want to replace all image src from paste object slice? sometimes slice images type are nested.

I copy some webpage and then paste it to prosemirror editor, the webpage contains img tags

so, I want to read the img tags and upload the img urls to my server and then fetch the image return my server image url to client, and then replace the img tags’s src.

1 Like

my solution, Any suggestion?

        slice.content.forEach(item => {
            if (item.type.name === 'image') {
                console.log(item.attrs.src);
                item.attrs.src = 'https://miro.medium.com/max/1400/0*G4NUYazg0MXMlvjc'
            }
            if (item.content) {
                item.content.forEach(i => {
                    if (i.type.name === 'image')
                    {
                        console.log(i.attrs.src);
                        i.attrs.src = 'https://miro.medium.com/max/1400/1*oscpiFUCJAFn5mZJxR3aYA.png'
                    }
                })
            }
        });

Yes, don’t do item.attrs.src = .... The docs are full of warnings about this. You can’t mutate the library’s data structures. That’ll break stuff. Create a new slice with the updated content you want. The easiest way to do that is probably with a recursive function that maps a given node to its updated form.

My 2 cents. One of possible solutions is to use Slice.toJSON / fromJSON and recursive JSON traversal in between.

function recursivelyReplaceInplaceB64WithObjectURL(node) {
  if (node.type === "image" && matchBase64Uri(node.attrs.src)) {
    const before = node.attrs.src;
    node.attrs.src = generateObjectUrlForBase64ImageSource(before, URL);
    return;
  }

  const content = node.content || [];
  for (let i = 0; i < content.length; i++) {
    recursivelyReplaceInplaceB64WithObjectURL(content[i]);
  }
}

export const transformSliceToReplaceBase64ImageSources = ({slice, schema}) => {
  const sliceJSON = slice.toJSON();

  recursivelyReplaceInplaceB64WithObjectURL(sliceJSON);

  return Slice.fromJSON(schema, sliceJSON);
};

Here we go. God bless ProseMirror.

Is there an example? I face the same situation too.