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

Cách nhúng khung nội tuyến (iframe) trong HTML?

Thẻ <iframe> (inline frame) nhúng trang HTML khác vào trang hiện tại. Dùng cho: video YouTube, bản đồ, widget, thanh toán, xác thực...

Thuộc tính chính

Thuộc tính Giá trị Mô tả
srcURLĐịa chỉ trang nhúng
width / heightpx, %Kích thước khung
nametextTên khung (dùng target của link/form)
sandboxallow-forms, allow-scripts, allow-same-origin, allow-top-navigation...Giới hạn quyền iframe (bảo mật)
allowcamera, microphone, geolocation, payment...Feature Policy (Permissions Policy)
referrerpolicyno-referrer, origin, strict-origin...Referrer gửi kèm
loadinglazy, eagerTải lười (lazy-load) iframe
frameborder0, 1Deprecated — dùng CSS border
scrollingyes, no, autoDeprecated — dùng CSS overflow

Ví dụ

<!DOCTYPE html>
<html>
  <head>
    <title>Thẻ iframe HTML</title>
  </head>
  <body>
    <iframe src="https://www.tutorialspoint.com/index.htm" width="100%" height="400" title="Tutorialspoint"></iframe>
  </body>
</html>

Bảo mật quan trọng

  • Luôn dùng sandbox cho iframe không tin cậy.
  • sandbox="allow-scripts allow-same-origin" cho phép JS nhưng giữ origin riêng.
  • Tránh allow-top-navigation trừ khi cần thiết.
  • Dùng X-Frame-Options / Content-Security-Policy: frame-ancestors để chặn site khác nhúng trang bạn.