C# sendmessage keypress

Windows Messages

The system passes input to a window procedure in the form of a message. Messages are generated by both the system and applications. The system generates a message at each input event—for example, when the user types, moves the mouse, or clicks a control such as a scroll bar. The system also generates messages in response to changes in the system brought about by an application, such as when an application changes the pool of system font resources or resizes one of its windows. An application can generate messages to direct its own windows to perform tasks or to communicate with windows in other applications.


The system sends a message to a window procedure with a set of four parameters: a window handle, a message identifier, and two values called message parameters. The window handle identifies the window for which the message is intended. The system uses it to determine which window procedure should receive the message.

A message identifier is a named constant that identifies the purpose of a message. When a window procedure receives a message, it uses a message identifier to determine how to process the message. For example, the message identifier WM_PAINT tells the window procedure that the window’s client area has changed and must be repainted.

Message parameters specify data or the location of data used by a window procedure when processing a message. The meaning and value of the message parameters depend on the message. A message parameter can contain an integer, packed bit flags, a pointer to a structure containing additional data, and so on. When a message does not use message parameters, they are typically set to NULL. A window procedure must check the message identifier to determine how to interpret the message parameters.

Cross-window messaging

The interface allows windows to talk to each other no matter which origin they are from.

So, it’s a way around the “Same Origin” policy. It allows a window from to talk to and exchange information, but only if they both agree and call corresponding JavaScript functions. That makes it safe for users.

The interface has two parts.

The window that wants to send a message calls postMessage method of the receiving window. In other words, if we want to send the message to , we should call .

Arguments:

The data to send. Can be any object, the data is cloned using the “structured cloning algorithm”. IE supports only strings, so we should complex objects to support that browser.
Specifies the origin for the target window, so that only a window from the given origin will get the message.

The is a safety measure. Remember, if the target window comes from another origin, we can’t read it’s in the sender window. So we can’t be sure which site is open in the intended window right now: the user could navigate away, and the sender window has no idea about it.

Specifying ensures that the window only receives the data if it’s still at the right site. Important when the data is sensitive.

For instance, here will only receive the message if it has a document from the origin :

If we don’t want that check, we can set to .

To receive a message, the target window should have a handler on the event. It triggers when is called (and check is successful).

The event object has special properties:

The data from .
The origin of the sender, for instance .
The reference to the sender window. We can immediately back if we want.

To assign that handler, we should use , a short syntax does not work.

Here’s an example:

The full example:

Result iframe.html index.html

How to Use postMessage

There are two basic components to cross-document messaging: the method invocation, and the event handler set up in the receiving document to respond to incoming messages.

To send a message from one document to another, begin by obtaining a reference to the window you want to send a message to. If sending a message to a document in an iframe, first get a reference to the iframe and then its property as shown . If sending a message from the iframed document to the containing document, the keyword provides a reference. (See example.)

If sending a message to a window opened using the method, a reference is returned from the method. If sending a message from a window opened using the method, the property of the window provides that reference.

postMessage Arguments

The method takes two arguments: the message to be sent (data), and the domain to which you wish to send it (formally referred to as the target origin):

The method supports data types including strings, numbers, arrays, and objects. However, some older browsers only support passing strings in postMessage. The method can be used to convert more complex data types to strings if you wish to support older browsers, as most of our demonstrate.

The target origin argument includes the protocol, host, and optionally, the port of the document to receive the message. Target origin can also be specified using an (any origin) or (the same origin as the document sending the message). If the origin of the target window doesn’t match the specified origin, the message is not sent.

The Message Event

When a message is sent using postMessage, a event is fired on the destination window. In order to process the event, you need a message event handler. You can use to assign a handler to the message event, including for Internet Explorer 8 if you like, or you can assign a function to the property of the window object.

An object is passed to the message event handler. The message includes the following properties:

data
the message being sent
origin
the origin of the document that sent the message (protocol, hostname, and possibly port)
source
a reference to the window object from which the message came

The following message event handler function demonstrates how these properties can be used:

Making a Request

Posting a message is a one-line request.

Let’s look at the parameters a little.

  • «testhandle»: A unique handle or ID to the iframe. Any request made to the domain will use this handle. This allows you to alias domains once they’ve been initialized.

  • «test»: The registered method within the other domain to execute. In this case «test». See above for how the other domain registered this function.

  • {somedata:values}: The JSON, string, boolean, numerical, or other primitive value you wish to send. You cannot send functions through postMessage!

  • «callbackMethod»: (Optional) A name for a previously registered callback that the first domain registered using the registerListener function. This can also be a function, which will make the system automatically register it with a custom name and delete it from the object later. See below.

    PM.postMessage(«testhandle», «test», {my:»test», test:»is good»}, function(data){ console.log(data); });

  • «http://otherdomain.com/PMWebpage.html»: (Optional*) A webpage to create an iframe for and post a message to. *This is only required upon first calling postMessage for that domain or unless you call the PM.preloadUrl() function.

The PM.preloadUrl function can be called upon page instantiation ( $(document).ready() ) to allow PM.js to create the iframes and initialize the other webpage to allow instantaneous postMessage requests once the iframe is fully loaded.


The PM.postMessage() function can be called immediately after the PM.preloadUrl() function without waiting.

Remarks

When a message is blocked by UIPI the last error, retrieved with GetLastError, is set to 5 (access denied).

Messages in a message queue are retrieved by calls to the GetMessage or PeekMessage function.

Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication.

The system only does marshalling for system messages (those in the range 0 to (WM_USER-1)). To send other messages (those >= WM_USER) to another process, you must do custom marshalling.

If you send a message in the range below WM_USER to the asynchronous message functions (PostMessage, SendNotifyMessage, and SendMessageCallback), its message parameters cannot include pointers. Otherwise, the operation will fail. The functions will return before the receiving thread has had a chance to process the message and the sender will free the memory before it is used.

Do not post the WM_QUIT message using PostMessage; use the PostQuitMessage function.

An accessibility application can use PostMessage to post WM_APPCOMMAND messages to the shell to launch applications. This functionality is not guaranteed to work for other types of applications.

There is a limit of 10,000 posted messages per message queue. This limit should be sufficiently large. If your application exceeds the limit, it should be redesigned to avoid consuming so many system resources. To adjust this limit, modify the following registry key.

HKEY_LOCAL_MACHINE
   SOFTWARE
      Microsoft
         Windows NT
            CurrentVersion
               Windows
                  USERPostMessageLimit

The minimum acceptable value is 4000.

Examples

The following example shows how to post a private window message using the PostMessage function. Assume you defined a private window message called WM_COMPLETE:

You can post a message to the message queue associated with the thread that created the specified window as shown below:

For more examples, see Initiating a Data Link.

Note

The winuser.h header defines PostMessage as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

Examples

: Press Win+O to turn off the monitor.

#o::
Sleep 1000  ; Give user a chance to release keys (in case their release would wake up the monitor again).
; Turn Monitor Off:
SendMessage, 0x112, 0xF170, 2,, Program Manager  ; 0x112 is WM_SYSCOMMAND, 0xF170 is SC_MONITORPOWER.
; Note for the above: Use -1 in place of 2 to turn the monitor on.
; Use 1 in place of 2 to activate the monitor's low-power mode.
return

: Start the user’s chosen screen saver:

SendMessage, 0x112, 0xF140, 0,, Program Manager  ; 0x112 is WM_SYSCOMMAND, and 0xF140 is SC_SCREENSAVE.

: Scroll up by one line (for a control that has a vertical scroll bar):

ControlGetFocus, control, A
SendMessage, 0x115, 0, 0, %control%, A

: Scroll down by one line:

ControlGetFocus, control, A
SendMessage, 0x115, 1, 0, %control%, A

: Switch the active window’s keyboard layout/language to English:

PostMessage, 0x50, 0, 0x4090409,, A  ; 0x50 is WM_INPUTLANGCHANGEREQUEST.

: This example asks Winamp which track number is currently active (see Automating Winamp for more information):

SetTitleMatchMode, 2
SendMessage, 1024, 0, 120,, - Winamp
if (ErrorLevel != "FAIL")
{
    ErrorLevel++  ; Winamp's count starts at "0", so adjust by 1.
    MsgBox, Track #%ErrorLevel% is active or playing.
}

: To find the process ID of an AHK script (an alternative to WinGet PID):

SetTitleMatchMode, 2
DetectHiddenWindows, On
SendMessage, 0x44, 0x405, 0, , SomeOtherScript.ahk - AutoHotkey v
MsgBox %ErrorLevel% is the process id.

ErrorLevel

: These commands are able to throw an exception on failure. For more information, see .

PostMessage: ErrorLevel is set to 1 if there was a problem such as the target window or control not existing. Otherwise, it is set to 0.

SendMessage: ErrorLevel is set to the word FAIL if there was a problem or the command timed out. Otherwise, it is set to the numeric result of the message, which might sometimes be a «reply» depending on the nature of the message and its target window.

The range of possible values depends on the target window and the version of AutoHotkey that is running. When using a 32-bit version of AutoHotkey, or if the target window is 32-bit, the result is a 32-bit unsigned integer between 0 and 4294967295. When using the 64-bit version of AutoHotkey with a 64-bit window, the result is a 64-bit signed integer between -9223372036854775808 and 9223372036854775807.

If the result is intended to be a 32-bit signed integer (a value from -2147483648 to 2147483648), it can be truncated to 32-bit and converted to a signed value as follows:

MsgReply := ErrorLevel << 32 >> 32

This conversion may be necessary even on AutoHotkey 64-bit, because results from 32-bit windows are zero-extended. For example, a result of -1 from a 32-bit window is seen as 0xFFFFFFFF on any version of AutoHotkey, whereas a result of -1 from a 64-bit window is seen as 0xFFFFFFFF on AutoHotkey 32-bit and -1 on AutoHotkey 64-bit.

Message Filtering

An application can choose specific messages to retrieve from the message queue (while ignoring other messages) by using the GetMessage or PeekMessage function to specify a message filter. The filter is a range of message identifiers (specified by a first and last identifier), a window handle, or both. GetMessage and PeekMessage use a message filter to select which messages to retrieve from the queue. Message filtering is useful if an application must search the message queue for messages that have arrived later in the queue. It is also useful if an application must process input (hardware) messages before processing posted messages.

The WM_KEYFIRST and WM_KEYLAST constants can be used as filter values to retrieve all keyboard messages; the WM_MOUSEFIRST and WM_MOUSELAST constants can be used to retrieve all mouse messages.

Any application that filters messages must ensure that a message satisfying the message filter can be posted. For example, if an application filters for a WM_CHAR message in a window that does not receive keyboard input, the GetMessage function does not return. This effectively «hangs» the application.

The “sandbox” iframe attribute

The attribute allows for the exclusion of certain actions inside an in order to prevent it executing untrusted code. It “sandboxes” the iframe by treating it as coming from another origin and/or applying other limitations.

There’s a “default set” of restrictions applied for . But it can be relaxed if we provide a space-separated list of restrictions that should not be applied as a value of the attribute, like this: .

In other words, an empty attribute puts the strictest limitations possible, but we can put a space-delimited list of those that we want to lift.

Here’s a list of limitations:

By default forces the “different origin” policy for the iframe. In other words, it makes the browser to treat the as coming from another origin, even if its points to the same site. With all implied restrictions for scripts. This option removes that feature.
Allows the to change .
Allows to submit forms from .
Allows to run scripts from the .
Allows to popups from the

See the manual for more.


The example below demonstrates a sandboxed iframe with the default set of restrictions: . It has some JavaScript and a form.

Please note that nothing works. So the default set is really harsh:

Result index.html sandboxed.html

Please note:

The purpose of the attribute is only to add more restrictions. It cannot remove them. In particular, it can’t relax same-origin restrictions if the iframe comes from another origin.

Security Considerations

The recommends the following steps to ensure the safety of the process when using cross-document messaging:

  • Check the origin attribute to ensure that messages are only accepted from domains that you expect to receive messages from.
  • If you don’t check the origin attribute and instead accept messages from any origin, keep in mind the potential risk for denial-of-service attacks. Controlling the number of messages accepted per minute could offer protection in this case.
  • Check the data received to be sure it is the type of data you are expecting.
  • Don’t use the wildcard target origin () when sending messages that contain confidential information.

Sending a Message

The SendMessage function is used to send a message directly to a window procedure. SendMessage calls a window procedure and waits for that procedure to process the message and return a result.

A message can be sent to any window in the system; all that is required is a window handle. The system uses the handle to determine which window procedure should receive the message.

Before processing a message that may have been sent from another thread, a window procedure should first call the InSendMessage function. If this function returns TRUE, the window procedure should call ReplyMessage before any function that causes the thread to yield control, as shown in the following example.

A number of messages can be sent to controls in a dialog box. These control messages set the appearance, behavior, and content of controls or retrieve information about controls. For example, the CB_ADDSTRING message can add a string to a combo box, and the BM_SETCHECK message can set the check state of a check box or radio button.

Use the SendDlgItemMessage function to send a message to a control, specifying the identifier of the control and the handle of the dialog box window that contains the control. The following example, taken from a dialog box procedure, copies a string from a combo box’s edit control into its list box. The example uses SendDlgItemMessage to send a CB_ADDSTRING message to the combo box.

Remarks

These commands should be used with caution because sending a message to the wrong window (or sending an invalid message) might cause unexpected behavior or even crash the target application. This is because most applications are not designed to expect certain types of messages from external sources.

PostMessage places the message in the message queue associated with the target window. It does not wait for acknowledgement or reply. By contrast, SendMessage waits for the target window to process the message, up until the timeout period expires.

The wParam and lParam parameters should be integers. If AutoHotkey or the target window is 32-bit, only the low 32 bits are used; that is, the value should be between -2147483648 and 4294967295 (0xFFFFFFFF). If AutoHotkey and the target window are both 64-bit, any integer value can be used. As with all integer values in AutoHotkey, a prefix of 0x indicates a hex value. For example, 0xFF is equivalent to 255.

A string may be sent via wParam or lParam by specifying the address of a variable. The following example uses the to do this:

SendMessage, 0xC, 0, &MyVar, ClassNN, WinTitle  ; 0XC is WM_SETTEXT

: A string put into MyVar by the receiver of the message is properly recognized without the need for extra steps. However, this works only if the parameter’s first character is an ampersand (&); for example, would not work but or would work.

A quoted/literal string may also be sent as in the following working example (the & operator should not be used in this case):

Run Notepad
WinWait Untitled - Notepad
SendMessage, 0xC, 0, "New Notepad Title"  ; 0XC is WM_SETTEXT

To send a message to all windows in the system, including those that are hidden or disabled, specify for WinTitle (0xFFFF is HWND_BROADCAST). This technique should be used only for messages intended to be broadcast, such as the following example:

SendMessage, 0x1A,,,, ahk_id 0xFFFF  ; 0x1A is WM_SETTINGCHANGE

To have a script receive a message, use OnMessage().

See the Message Tutorial for an introduction to using these commands.

Window titles and text are case sensitive. Hidden windows are not detected unless DetectHiddenWindows has been turned on.

Pages

Create the following files

Page1.html (note the sendMessage function)

<!DOCTYPE html><html><head>    <title></title> <meta charset="utf-8" /><script>var childwin;const childname = "popup";function openChild() {childwin = window.open('Page2.html', childname, 'height=300px, width=500px');}function sendMessage(){    let msg={pName : "Bob", pAge: "35"};    // In production, DO NOT use '*', use toe target domain    childwin.postMessage(msg,'*')// childwin is the targetWindow    childwin.focus();}</script></head><body>    <form>        <fieldset>            <input type='button' id='btnopen' value='Open child' onclick='openChild();' />            <input type='button' id='btnSendMsg' value='Send Message' onclick='sendMessage();' />        </fieldset>    </form></body></html>

Page2.html (note callback function in addEventListener)

<!DOCTYPE html><html><head>    <title></title>    <meta charset="utf-8" />    <script>// Allow window to listen for a postMessage    window.addEventListener("message", (event)=>{// Normally you would check event.origin        // To verify the targetOrigin matches        // this window's domain        let txt=document.querySelector('#txtMsg');        // event.data contains the message sent        txt.value=`Name is ${event.data.pName} Age is  ${event.data.pAge}` ;    });function closeMe() {        try {window.close();        } catch (e) { console.log(e) }        try {self.close();        } catch (e) { console.log(e) }}    </script></head><body>    <form>        <h1>Recipient of postMessage</h1>            <fieldset>                <input type='text' id='txtMsg' />                <input type='button' id='btnCloseMe' value='Close me' onclick='closeMe();' />            </fieldset>    </form></body></html>

Inspiration

You may have heard about easyXDM by now if you’ve been googling for an answer to postMessage or cross-domain communication.

I developed this solution as a way to memorialize the knowledge that I gained as the lead developer of Disney’s latest login website. At first we utilized easyXDM for much of the postMessage internals, using a 3 tiered iframe approach, which led to huge delays in the request times.

After much improvements to the internals, we began implementing a 2 tiered approach using the parent website and the internal iframe which pointed to our login website. Without going into further detail, this solution is based on the initial understanding of easyXDM’s RPC calls, and the knowledge from working extensively with postMessage requests.

Examining a Message Queue

Occasionally, an application needs to examine the contents of a thread’s message queue from outside the thread’s message loop. For example, if an application’s window procedure performs a lengthy drawing operation, you may want the user to be able to interrupt the operation. Unless your application periodically examines the message queue during the operation for mouse and keyboard messages, it will not respond to user input until after the operation has completed. The reason for this is that the DispatchMessage function in the thread’s message loop does not return until the window procedure finishes processing a message.

You can use the PeekMessage function to examine a message queue during a lengthy operation. PeekMessage is similar to the GetMessage function; both check a message queue for a message that matches the filter criteria and then copy the message to an MSG structure. The main difference between the two functions is that GetMessage does not return until a message matching the filter criteria is placed in the queue, whereas PeekMessage returns immediately regardless of whether a message is in the queue.

The following example shows how to use PeekMessage to examine a message queue for mouse clicks and keyboard input during a lengthy operation.

Other functions, including GetQueueStatus and GetInputState, also allow you to examine the contents of a thread’s message queue. GetQueueStatus returns an array of flags that indicates the types of messages in the queue; using it is the fastest way to discover whether the queue contains any messages. GetInputState returns TRUE if the queue contains mouse or keyboard messages. Both of these functions can be used to determine whether the queue contains messages that need to be processed.

Обмен сообщениями между окнами

Интерфейс позволяет окнам общаться между собой независимо от их происхождения.

Это способ обойти политику «Одинакового источника». Он позволяет обмениваться информацией, скажем и , но только в том случае, если оба сайта согласны и вызывают соответствующие JavaScript-функции. Это делает общение безопасным для пользователя.

Интерфейс имеет две части.

Окно, которое хочет отправить сообщение, должно вызвать метод postMessage окна получателя. Другими словами, если мы хотим отправить сообщение в окно , тогда нам следует вызвать .

Аргументы:

Данные для отправки. Может быть любым объектом, данные клонируются с использованием «алгоритма структурированного клонирования». IE поддерживает только строки, поэтому мы должны использовать метод на сложных объектах, чтобы поддержать этот браузер.
Определяет источник для окна-получателя, только окно с данного источника имеет право получить сообщение.

Указание является мерой безопасности. Как мы помним, если окно (получатель) происходит из другого источника, мы из окна-отправителя не можем прочитать его . Таким образом, мы не можем быть уверены, какой сайт открыт в заданном окне прямо сейчас: пользователь мог перейти куда-то, окно-отправитель не может это знать.

Если указать , то мы можем быть уверены, что окно получит данные только в том случае, если в нём правильный сайт

Особенно это важно, если данные конфиденциальные

Например, здесь получит сообщения только в том случае, если в нём открыт документ из источника :


Если мы не хотим проверять, то в можно указать .

Чтобы получать сообщения, окно-получатель должно иметь обработчик события (сообщение). Оно срабатывает, когда был вызван метод (и проверка пройдена успешно).

Объект события имеет специфичные свойства:

Данные из .
Источник отправителя, например, .
Ссылка на окно-отправитель. Можно сразу отправить что-то в ответ, вызвав .

Чтобы добавить обработчик, следует использовать метод , короткий синтаксис не работает.

Вот пример:

Полный пример:

Результат iframe.html index.html

Без задержек

Между и событием не существует задержки. Событие происходит синхронно, быстрее, чем .

How to Find LParam

  • First, you must download Microsoft spy++. If you install Microsoft Visual 2012, Microsoft spy ++ will be integrated
  • I will demo how to get with , value through some basic steps (Same as, you can do it with , , …. key)
  • Now open Notepad by run -> notepad
  • Open your Microsoft Spy ++ (Built-in Microsoft Visual Studio 2012 ++)

Next, Click to menu Spy -> FindWindows, using cross circle on the red frame.

Drag this cross circle to Notepad on this edit area:

Click choose Messages properties same as the below picture. Then click ok.

Let’s press RETURN key to Edit Area, you can easily see message on Microsoft Spy++ Dash Broad. Then, right click to that message and choose properties, you can easily know and value.

My value found: and value:

::PostMessage(hHandle, WM_KEYDOWN, VK_RETURN, 0x001C0001);

::SendMessage(hHandle, WM_KEYDOWN, VK_RETURN, 0x001C0001);

Using the Source Code

Using and

API for get window handle:

HWND hwnd = FindWindowA("Notepad", NULL );
HWND hWndChild = ::FindWindowEx(hwnd, NULL, L"Edit", NULL);
BOOL CReadInfomationGameDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    

    
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        CString strAboutMenu;
        strAboutMenu.LoadString(IDS_ABOUTBOX);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    
    
    SetIcon(m_hIcon, TRUE);   
    SetIcon(m_hIcon, FALSE);  
    
    
    CString strCommand[] =  
    {

        L"learn-tech-tips",
        L"http://learn-tech-tips.blogspot.com",
        L"huuvi168@gmail.com",
        L"zidane"
        L"http://www.codeproject.com/Tips/1025019/Get-Server-Side-Data-time-with-Cplusplus",
    };

    int length = sizeof(strCommand) / sizeof(strCommand[]);
    for (int i=; i<length; i++)
        m_cbCommand.AddString(strCommand);
 
 
    return TRUE;  
}

HWND CReadInfomationGameDlg::GetHandleOfWindow(void)
{ 
    HWND hwnd = FindWindowA("Windows abc Class", NULL ); 

    if (!hwnd) 
    {
        MessageBox(_T("Window abc not found"), _T("Message"), MB_OK 
                                                    | MB_ICONINFORMATION);  
        return NULL;
    } 
 
    return hwnd;
}

void CReadInfomationGameDlg::OnBnClickedButtonAddmessage()
{
    
    HWND hHandle = GetHandleOfWindow();

    CString strCBText;
    int nIndex = m_cbCommand.GetCurSel();
 
    if (nIndex == -1) 
    {
        TCHAR strTemp;  
        memset(strTemp, 0x00, sizeof(strTemp));
        GetDlgItemText(IDC_COMBO_COMMAND, strTemp, sizeof(strTemp));
        PostChatMessage(hHandle, strTemp);
    }
    else 
    {
        m_cbCommand.GetLBText(nIndex, strCBText); 
        PostChatMessage(hHandle, strCBText);
    }
}

void CReadInfomationGameDlg::PostChatMessage(HWND hHandle, LPCTSTR szChatMsg)
{
     ::PostMessage(hHandle, WM_KEYDOWN, VK_RETURN, 0x001C0001);
     ::PostMessage(hHandle, WM_KEYDOWN, VK_DOWN, 0x00500001);

    while (szChatMsg[])
    {
        ::PostMessage(hHandle, WM_CHAR, LOBYTE(szChatMsg[]),);
        szChatMsg++;
    }

    ::PostMessage(hHandle, WM_KEYDOWN, VK_RETURN, 0x001C0001);
}

Details

Sends a chat message of the specified in ‘msg’ (ex. «Hey!»), to the system specified in ‘chatType’ («SAY», «WHISPER», «EMOTE», «CHANNEL», «PARTY», «BATTLEGROUND», «GUILD», «OFFICER», «YELL», «RAID», «RAID_WARNING», «AFK», «DND»), in the language specified in ‘language’ («COMMON», «DARNASSIAN», «DWARVISH», «TAURAHE», «ORCISH», «GUTTERSPEAK», «DEMONIC», «DRACONIC», «KALIMAG», «TITAN», «GNOMISH»), to the player or channel specified in ‘channel'(ex. «1», «Bob»).
Notes
  • The earliest you can send a chat message to «GUILD» is after the event «CLUB_STREAM_SUBSCRIBED» is fired, as this is when the Community channel is loaded. (Guild is a Community channel)
  • «AFK» and «DND» set your AFK or DND auto-reply. To cancel afk/dnd status, send another message to the same ‘channel’.

It should be noted that you must provide a ‘language’ (be it nil or an actual language name) before the ‘channel’ when sending to the «WHISPER» or «CHANNEL» system.

To send a whisper to the player’s selected target, use UnitName(«target») as the Channel.

Patch 1.11.0 added the «RAID_WARNING» system, only usable by the raid leader and raid assistants. The default UI shows messages send via «RAID_WARNING» in big letters on the center of the screen. As of a recent change in patch 2.0.0 this is also available in party and usable by all party member; Please don’t abuse this idea.

Some channels may have restrictions on who may speak in them. For example, in order to speak in the ‘World Defense’ channel, you must have a PvP rank of 11 or higher.

Patch 2.0.0 throws an error when trying to speak a language you don’t know.

«Trying to spoof item links will disconnect you.» — directly taken from patch 1.10.0 patch changes. This includes miscontructed link strings of genuine items/spells/tradeskills, such as capitalizing the hex codes for the link colors.

As of patch 2.4.0 (or 2.3?), you are no longer disconnected when sending over-long messages. The message is silently truncated to 255 characters.

patch 2.4: Sending 10+ messages at a time resulting in high RTT for the 9+ messages. (se «Discussion» page for more info)

Iframe: wrong document pitfall

When an iframe comes from the same origin, and we may access its , there’s a pitfall. It’s not related to cross-origin things, but important to know.

Upon its creation an iframe immediately has a document. But that document is different from the one that loads into it!

So if we do something with the document immediately, that will probably be lost.

Here, look:

We shouldn’t work with the document of a not-yet-loaded iframe, because that’s the wrong document. If we set any event handlers on it, they will be ignored.

How to detect the moment when the document is there?

The right document is definitely at place when triggers. But it only triggers when the whole iframe with all resources is loaded.

We can try to catch the moment earlier using checks in :

Summary

To call methods and access the content of another window, we should first have a reference to it.

For popups we have these references:

  • From the opener window: – opens a new window and returns a reference to it,
  • From the popup: – is a reference to the opener window from a popup.

For iframes, we can access parent/children windows using:

  • – a collection of nested window objects,
  • , are the references to parent and top windows,
  • is the window inside an tag.

If windows share the same origin (host, port, protocol), then windows can do whatever they want with each other.

Otherwise, only possible actions are:

  • Change the of another window (write-only access).
  • Post a message to it.

Exceptions are:

  • Windows that share the same second-level domain: and . Then setting in both of them puts them into the “same origin” state.
  • If an iframe has a attribute, it is forcefully put into the “different origin” state, unless the is specified in the attribute value. That can be used to run untrusted code in iframes from the same site.

The interface allows two windows with any origins to talk:

  1. The sender calls .

  2. If is not , then the browser checks if window has the origin .

  3. If it is so, then triggers the event with special properties:

    • – the origin of the sender window (like )
    • – the reference to the sender window.
    • – the data, any object in everywhere except IE that supports only strings.

    We should use to set the handler for this event inside the target window.


С этим читают