1

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

2 回答 2

1

好的,我想出了一个令人满意的解决方案。我需要在调用之前appendChild()定义 iframe 名称。

<html>
  <head>
    <title>Google Preview</title>
    <style>iframe { width: 800px; height: 600px }</style>
  </head>
  <body>
    <div><a target="results" href="http://www.google.com">test</a></div>
    <script>
      try {
        // this works
        const iframe = document.createElement('iframe');
        iframe.name = 'results';
        document.body.appendChild( iframe );
      } catch (e) {
        alert(e);
      }
    </script>
  </body>
</html>

我不确定为什么在将名称附加到文档后设置名称不起作用(我仍然想知道是否有人想要 15 分),但这让我可以继续使用 GreaseMonkeying,所以它已经足够好了.

于 2009-05-23T04:00:55.177 回答
-1

嗯,我在想,因为它仍在回发给自己,所以永远不会创建框架(因为每次回发时都会在页面上创建和呈现表单)

于 2009-05-22T18:29:52.277 回答