Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách gửi tin nhắn chéo tài liệu với HTML

Tạo một ngữ cảnh duyệt web mới bằng cách tạo iframe mới hoặc cửa sổ mới. Chúng ta có thể gửi dữ liệu bằng postMessage() với hai đối số:

  • message – Tin nhắn cần gửi
  • targetOrigin – Nguồn gốc đích

Ví dụ gửi tin nhắn từ iframe đến nút bấm:

var iframe = document.querySelector('iframe');
var button = document.querySelector('button');
var clickHandler = function(){
    iframe.contentWindow.postMessage('The message to send.', 'https://www.tutorialspoint.com');
}
button.addEventListener('click', clickHandler, false);