Insert img whith PostMessage API

I’m having trouble sending an image to the document with the postmessage API, I created a customizable button to do this, and I’m getting the document’s returns, when the button is selected I send the image to the document, but the image is not inserted, Note: I’m using iframe

receiveMessage(event) {
let jsonData = ‘’;
if(typeof event.data === ‘object’) {
jsonData = event.data;
}
else {
jsonData = JSON.parse(event.data);
}
console.log("Message received from the child: ", jsonData); // Message received from child
const protocol = window.location.protocol;
const host = window.location.host;
const port = window.location.port ? :${window.location.port} : ‘’;

    // Formar a URL base
    const baseUrl = `${protocol}//${host}`;

    if(jsonData.MessageId == "Clicked_Button") {
        if(jsonData.Values.Id == "brasao__") {
            document.getElementById('edicaoTextoDescricao').contentWindow.postMessage(
                JSON.stringify({'MessageId': 'Send_UNO_Command',
                'Values': {
                    'Command': '.uno:DefaultFormat',
                    'Args': {}
                }
                }), '*');

            document.getElementById('edicaoTextoDescricao').contentWindow.postMessage(
                JSON.stringify({
                    MessageId: 'Send_UNO_Command',
                    'Values': {
                      'Command': '.uno:InsertHeader',
                      'Args': {}
                    }
                  }), '*');    

                

            document.getElementById('edicaoTextoDescricao').contentWindow.postMessage(
                JSON.stringify({'MessageId': 'Send_UNO_Command',
                    'Values': {
                    'Command': '.uno:CenterPara',
                    'Args': {}
                    }
                }), '*'); 


           
            var urlImg = baseUrl + '/ui/img/brasao.png';
            urlImg = urlImg.toString();
            document.getElementById('edicaoTextoDescricao').contentWindow.postMessage(
                JSON.stringify({
                    MessageId: "Action_InsertGraphics",
                    Values: {
                        url: urlImg,
                    }
            }), '*');
            
            

            

            setTimeout(function() {

                document.getElementById('edicaoTextoDescricao').contentWindow.postMessage(
                    JSON.stringify({'MessageId': 'Send_UNO_Command',
                    'Values': {
                        'Command': '.uno:InsertText',
                        'Args': {
                            Text: {
                                type: 'string',
                                value: 'PODER JUDICIÁRIO\r\n'
                                +' Tribunal de Justiça do Estado de Goiás\r\n'
                                +' Gabinete da Presidência\r\n'
                                },
                            ParaStyleName: {
                                type: 'string',
                                value: 'Heading 1' // Estilo de cabeçalho pré-definido
                                }
                        }
                    }
                    }), '*');
            }, 1000);
        }

        if(jsonData.Values.Id == "abrir__") { 
            if(document.getElementById("formFile") != null && document.getElementById("formFile") != undefined) {
                document.getElementById("formFile").click();
            }
        }
    }

    if(jsonData.Values!= undefined && jsonData.Values.Status == "Document_Loaded" && document.getElementById('edicaoTextoDescricao') != null && document.getElementById('edicaoTextoDescricao') != undefined) {
        document.getElementById('edicaoTextoDescricao').contentWindow.postMessage(JSON.stringify({
            "MessageId" : "Insert_Button",
            "Values" : {
              "id" : "abrir__",
              "imgurl" : baseUrl + "/ui/img/folder.svg",
              "hint" : "Abrir",
              "insertBefore" : 'save',
              "label" : "Abrir"
            }
          }), '*');

          document.getElementById('edicaoTextoDescricao').contentWindow.postMessage(JSON.stringify({
            "MessageId" : "Insert_Button",
            "Values" : {
              "id" : "brasao__",
              "imgurl" : baseUrl + "/ui/img/brasao.png",
              "hint" : "Adicionar Brasão",
              "insertBefore" : 'save',
              "label" : "Brasão"
            }
          }), '*');
    }
}

Hey @TawanGMenezes, welcome to the forum. :slight_smile:

Are you successfully getting other PostMessage API stuff working, but just this image insertion is giving you trouble?


Note: I also see this paragraph in the API page:

It is to be noted that as mentioned in WOPI specs, Collabora Online frame will ignore all post messages coming from the host frame if Host_PostmessageReady has not been received. Further, since for embedding Collabora Online as an iframe WOPI implementation is a must, it is required that PostMessageOrigin property is present in WOPI host’s CheckFileInfo response. Otherwise, no post messages will be emitted.

Do you think this applies to your case?


Also helpful would be:

  • What browser/OS are you using?
  • Which Collabora version?

Oh? Sounds interesting. What are you trying to accomplish with your custom button? :slight_smile:

all PostMessage API not work. but i’m sure “Note: I also see this paragraph in the API page:"
version:Collabora 25.04

hi @jessie can you please explain what is the exact issue with post message API you are facing right now?

The “PostMessage” message was successfully sent, but no response was received from the editor, and no error log was captured. Only a warning log was generated.

wsd-00001-00044 2026-03-09 15:05:59.729656 +0800 [ docbroker_001 ] WRN Client session [004] not found to forward message: o719 unloaded: viewid=5 views=1| wsd/DocumentBroker.cpp:5324

The implementation of a similar screenshot function through the api failed, but there were no exception logs. The implementation code is as follows:

const frame = document.getElementById('collaboraFrame');
frame.contentWindow.postMessage({'MessageId': 'Action_FollowUser',
    'Values': {
        'Follow': true
    }
}, '*');

Summary

This text will be hidden

Hi @jessie

Thanks for the logs and screenshot

The warning in the log indicates that Collabora Online could not find the client session when the message was forwarded:

Client session [004] not found to forward message
o719 unloaded

This usually means the document or view session was already unloaded when the postMessage was sent. So the message is delivered to the iframe, but the editor backend no longer has an active session for that view, therefore no response is returned.

Suggested checks:

  • Ensure the message is sent only after the editor is fully loaded.
  • Listen for the message event from the iframe and wait for something like:

Example approach:

window.addEventListener('message', function(e) {
    if (e.data && e.data.MessageId === 'App_LoadingStatus' &&
        e.data.Values && e.data.Values.Status === 'Document_Loaded') {

        const frame = document.getElementById('collaboraFrame');
        frame.contentWindow.postMessage({
            MessageId: 'Action_FollowUser',
            Values: { Follow: true }
        }, '*');
    }
});

Above is example not exact implementation. just for your reference…

This ensures the document session and view are active before sending the action message.

Also note that if you are trying to implement a screenshot-like feature, the Action_FollowUser message will not produce a response unless the editor has an active session and valid view.


Below is my code, refer to the PostMessage API. But the expected effect has still not been achieved. Are there any other reasons?
window.addEventListener('message', function(event) {
    let msg;
    if(typeof event.data === 'object') {
        msg = event.data;
    } else {
        msg = JSON.parse(event.data);
    }
    console.log('Received message:', event.data);

    // handle App_LoadingStatus message
    if (msg.MessageId === 'App_LoadingStatus') {
        const status = msg.Values?.Status;

        if (status === 'Initialized') {
            const frame = document.getElementById('collaboraFrame');
            frame.contentWindow.postMessage({
                'MessageId': 'Host_PostmessageReady'
            }, '*');

            console.log('Initialized, send Host_PostmessageReady');
        }

        if (status === 'Document_Loaded') {
            console.log('document load successfully, the editor is ready');
            const frame = document.getElementById('collaboraFrame');
            frame.contentWindow.postMessage({
                'MessageId': 'Action_FollowUser',
                'Values': {
                    'Follow': true
                }
            }, '*');

            console.log('Document_Loaded, send Action_FollowUser');
        }
    }
});


Other info:
Collabora version: "25.04.9.1"
Server url:http://ip:9980
Deployment method: Linux deployment
The background: Nextcloud and Collabora have been successfully installed, but the code test failed.

Hi darshan,

With the PostMessage API, “MessageId”:“FollowUser_Changed” has a wrong response.

Manually click follow, the response will be right.

What could be the possible error?

contentWindow’s viewId = 6.

[send] Action_FollowUser Object { Follow: true, ViewId: “5” }

ViewId has tried string/integer,or not passing this field

Best regards,

Jessie

Hi Jessie,

Thanks for sharing the details and logs. I think the issue comes down to a couple of things:

1. Missing ViewId in your PostMessage call

Action_FollowUser needs to know which user’s view to follow. Right now you’re only sending Follow: true without specifying a target. Try this instead:

frame.contentWindow.postMessage({
    'MessageId': 'Action_FollowUser',
    'Values': {
        'ViewId': <target_view_id>,
        'Follow': true
    }
}, '*');

Replace <target_view_id> with the ViewId of the other user you want to follow. NOT YOUR OWN

2. Make sure a second user is present in the session

You mentioned your contentWindow’s viewId is 6. Follow only works when there’s another user with a different ViewId in the same document session. If you’re the only one in the session, there’s nobody to follow, which would explain the wrong response.

3. Timing — listen for View_Added instead of firing on Document_Loaded

Even if a second user is present, their view may not be registered yet at the time Document_Loaded fires. Instead of sending Action_FollowUser immediately on Document_Loaded, listen for the View_Added message first. That way you’ll know another user’s view is available and you’ll also have their ViewId.

Something like this:

if (msg.MessageId === 'View_Added') {
    const targetViewId = msg.Values?.ViewId;
    console.log('New view added:', targetViewId);

    const frame = document.getElementById('collaboraFrame');
    frame.contentWindow.postMessage({
        'MessageId': 'Action_FollowUser',
        'Values': {
            'ViewId': targetViewId,
            'Follow': true
        }
    }, '*');
}

Let me know how it goes!

Best,
Darshan

Hi darshan,

1.I’m sure all the steps are as you said.

2.add the code “3. Timing — listen for View_Added instead of firing on Document_Loaded

screenshots as below:

flush user2,

Jessie,

Thanks for the screenshots. I understand the situaction now

The FollowUser_Changed response is returning your own ViewId as FollowedViewId instead of the target user’s ViewId. Since manual clicking works correctly but PostMessage doesn’t, this looks like a bug in Collabora’s PostMessage API for Action_FollowUser.

@jessie Can you help to file this bug ?

Two things to try before filing a bug:

  1. Try sending ViewId as a string'ViewId': String(targetViewId) instead of a number
  2. Try the UNO command directly:
frame.contentWindow.postMessage({
    'MessageId': 'Send_UNO_Command',
    'Values': {
        'Command': '.uno:FollowUser',
        'Args': {
            'ViewId': {
                'type': 'long',
                'value': targetViewId
            }
        }
    }
}, '*');

Also, quick check is the follow actually working visually even though the response is wrong? Open both windows side by side and see if user2’s view follows user1’s cursor movements.

If nothing helps, I’d suggest filing this as a bug on Collabora Online GitHub with your screenshots.

Best,
Darshan

Hi Darshan,

Two things were tried, and the results were the same.

The follow does not working visually.

User2’s view does not follow User1’s cursor movements.

Best regards,

Jessie

so best to file bug report then as i already suggested

Thanks
Darshan

Thanks for filling the issue @jessie PostMessage API Action_FollowUser do not work correctly · Issue #15069 · CollaboraOnline/online · GitHub

I hope we can discuss more on Github and i will update as soon as this gets fix :slight_smile:

Thanks
Darshan