因此,在纯 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>