【发布时间】:2010-10-28 07:23:44
【问题描述】:
所以,在纯 HTML 中,我可以创建一个将其结果加载到 iframe 中的表单 (而不是将用户移动到结果 url)。
<html>
<head>
<title>Google Preview</title>
<style>iframe { width: 800px; height: 600px }</style>
</head>
<body>
<form method='get' action='http://www.google.com/search' target='results'>
<label for='q'>Google Search:</label>
<input name='q'/>
</form>
<!-- form result loads in this iframe -->
<iframe name='results'></iframe>
</body>
</html>
我正在尝试在 Greasemonkey 中做类似的事情,但遇到了问题。
我有一个带有表单的页面,我希望将其结果加载到 iframe 中,
所以我创建了一个 iframe,并更改了 target 的形式以匹配 iframe 的名称。
但是,这不会在 iframe 中加载结果页面,而是打开
新标签页中的结果页面。
我已将问题追溯到使用 Javascript 创建 iframe。它似乎
将 iframe 插入 DOM 就好了(并查看 firebug,源
生成的几乎与上面相同,除了一个额外的<script> 标签)。
但是当我在 Javascript 中创建 iframe 时,我得到“在新选项卡中打开结果”
行为。
<html>
<head>
<title>Google Preview</title>
<style>iframe { width: 800px; height: 600px }</style>
</head>
<body>
<form method='get' action='http://www.google.com/search' target='results'>
<label for='q'>Google Search:</label>
<input name='q'/>
</form>
<script>
try {
// form result doesn't load in this iframe, for some reason
const iframe = document.body.appendChild( document.createElement('iframe') );
iframe.name = 'results';
} catch (e) {
alert(e);
}
</script>
</body>
</html>
我需要做什么才能将结果加载到由 Javascript 创建的 iframe 中? (我还没有尝试过document.write(),但我不确定这对 Greasemonkey 是否有用)。
更新:所以我开始尝试document.write(),它确实有效。所以也许我只需要弄清楚如何从 GreaseMonkey 中使用它(不会弄乱我有句柄的大量 DOM 元素)
<html>
<head>
<title>Google Preview</title>
<style>iframe { width: 800px; height: 600px }</style>
</head>
<body>
<form method='get' action='http://www.google.com/search' target='results'>
<label for='q'>Google Search:</label>
<input name='q'/>
</form>
<script>
try {
// but form result will load in this iframe
document.write('<iframe name="results"></iframe>');
} catch (e) {
alert(e);
}
</script>
</body>
</html>
我仍然想知道为什么document.body.appendChild() 不起作用,但document.write() 起作用。
更新2:它似乎不仅仅是表单,我可以用一个链接代替<form>...</form> 并获得所有三个相同的结果案例
<div><a target="results" href="http://www.google.com">test</a></div>
【问题讨论】:
标签: javascript html forms iframe greasemonkey