JavaScript 将文本放在 iFrame 的文本区域中

JavaScript put text in textarea within iFrame

本文关键字:文本 区域 iFrame JavaScript      更新时间:2023-09-26

是否可以使用 JavaScript 将文本放在 iFrame 的文本区域中?

索引.html

<iframe src="http://othersite.com:3000">

在iFrame中有一个文本区域

<textarea class="inp" placeholder="Send message..."></textarea>

是否可以在其中放置文本?

你不能修改iFrame的HTML,解决方案:必须使用postMessage。如果你不能修改"http://othersite.com:3000"的代码,那是不可能的。

如果可以,请尝试以下操作:

第 1 步:加载时向 iFrame 发送消息

$('#iframe').load(function(){
    source = $('iframe')[0].contentWindow;
    source.postMessage('hi', 'http://othersite.com:3000');
});

设置2:接收"http://othersite.com:3000"消息并修改文本区域值

$(document).ready(function(){
  window.addEventListener("message", function(e){
    if(e.origin === 'http://yourwebsite'){
      $('.inp').val('put your text here');
    }
  }, false)
}

我认为它第一次不会起作用,阅读文档并尝试保持相同的方式:)希望对您有所帮助