LoginSignup
2
2

More than 5 years have passed since last update.

Google ChromeでPOSTパラメータをF5更新で引き継ぐ

Last updated at Posted at 2017-08-16

追記:現在(60.0.3112.101)ではChromeのアップデートによりpostパラメータが取れるようになったため、この対応をしなくても正常動作します。Goggleさん・・・

Google ChromeでPOSTパラメータをF5更新で引き継ぐ

postで開いたページをGoogle ChromeでF5更新をするとpostパラメータが空になってしまう・・・
いつの間にこんな仕様変更が・・・
Googleさんやってくれましたね・・・
という事で対策しました。

Before

index.php
<html>
  <body>
    <form method="post" action="./">
      <input type="text" value="test" name="a" />
      <input type="submit" value="submit" />
    </form>
    <?php var_dump($_POST) ?>
  </body>
</html>

この状態では、submitした後にF5更新すると$_POSTが空になってしまう。

After

index.php
<html>
  <body>
    <form method="post" action="./">
      <input type="text" value="test" name="a" />
      <input type="submit" value="submit" />
    </form>
    <?php var_dump($_POST) ?>
    <?php
    echo f5reloadForm();
    function f5reloadForm()
    {
      $result = '';
      if (!empty($_POST)) {
        $result .= '<form method="post" id="reload_form" action="">';
        foreach ($_POST as $key => $value) {
          $result .= makeTag($key, $value);
        }
        $result .= '</form>';
        $result .= PHP_EOL;
        $result .= <<<JS
<script language="JavaScript"><!--
window.document.onkeydown = function (event)
{
  if (event.keyCode == 116) {
    var target = document.getElementById("reload_form");
    target.action = location.href;
    target.submit();
    return false;
  }
}
//--></script>
JS;
      }
      return $result;
    }
    function makeTag($key, $value)
    {
      $result = '';
      if (is_array($value)) {
        foreach ($value as $k => $v) {
          $result .= makeTag(sprintf('$s[%s]', $key, $k), $v);
        }
      } else {
        $result = sprintf('<input name="%s" value="%s" type="hidden" />', $key, $value);
      }
      return $result;
    }
    ?>
  </body>
</html>

F5更新用の擬似formを作ってpostパラメータ全てをhiddenに格納。
F5を押したときに擬似formをsubmitする事でF5更新と同等の挙動をするようにしました。

欠点

  1. Ctrl+F5が実質使えない
  2. ブラウザのリロードボタンは対策できていない

対策は不十分ですが、何も対策できていないより良いよね♪

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2