简体   繁体   English

将iframe的src =“”更改为javascript:

[英]Change src=“” of iframe to javascript:

I am trying to change the source of the iframe to javascript:... I tried this without any luck; 我正在尝试将iframe的源代码更改为javascript:...我尝试此操作没有任何运气;

<iframe id="iframed" src="http://example.com"></iframe>

$('#iframed').attr('src','javascript:document.write("hello world")');

I am getting "TypeError: document.write is not a function" error. 我收到“ TypeError:document.write不是函数”错误。 What is the correct way to do that ? 正确的做法是什么?

If you just want to write content to the frame, you can get direct access to its document object: 如果仅要将内容写入框架,则可以直接访问其文档对象:

document.getElementById("iframed").contentDocument.write("Hello World!");

This won't work if the frame is already loaded from a foreign domain however. 但是,如果框架已从外部域加载,则无法使用。

There is no standard I know of which defines what should happen when you set the src attribute on an iframe to a URI with the javascript: scheme. 我不知道有哪个标准定义了当您使用javascript:方案将iframe上的src属性设置为URI时应该发生什么。 There is a draft IETF note which suggests what functionality already exists (like its use in anchor elements), but does not say user agents have to do anything. IETF一份草稿草案 ,其中提出了已经存在的功能(例如其在锚元素中的使用),但并未说明用户代理必须做任何事情。 The fact that you can enter it into the address bar of a browser is due to the browser's implementation. 您可以将其输入到浏览器的地址栏中的事实归因于浏览器的实现。 For instance, I'm guessing entering that URL into a command-line browser like lynx would get you nowhere. 例如,我猜想在像lynx这样的命令行浏览器中输入该URL将无济于事。

If you want to communicate between frames using JavaScript, that would be a different question. 如果要使用JavaScript在框架之间进行通信,那将是另一个问题。

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <iframe id="iframed"></iframe>
        <script>
         var test = "Hello World!";
         document.getElementById("iframed").src = "data:text/html;charset=utf-8," + test;
        </script>
    </body>
</html>

Try this it works in chrome...also check out this link 尝试一下,它可以在chrome中使用...也请查看此链接

Since you're trying to put content additional content inside the iframe, you first need to know that it's likely to be impossible if you have no control over the site inside the frame (in your example " http://exemple.com "). 由于您正在尝试将内容添加到iframe中,因此您首先需要知道,如果您无法控制框架中的网站(在您的示例中为“ http://exemple.com ”),这可能是不可能的。 。

Else it would be easy to inject scripts, which would cause various security issues. 否则,注入脚本将很容易,这将导致各种安全问题。

If you have control over the site inside the iframe, you may make it able to understand messages originating from the site including the iframe. 如果您可以控制iframe内的网站,则可以使其理解来自该网站(包括iframe)的邮件。 If you want to do this way, you may want to look at "How to communicate between iframe and the parent site?" 如果您想采用这种方式,则可能需要查看“如何在iframe和父网站之间进行通信?”。 .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM