因此,在纯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()。
做。
更新
二
:它似乎不只是表单,我可以用一个链接代替
<form>...</form>
三个案例的结果都一样
<div><a target="results" href="http://www.google.com">test</a></div>