LoginSignup
1
1

More than 5 years have passed since last update.

色んなディレクトリに対応したデバイス振り分けリダイレクト

Posted at
// スマホの判定
const isMobile = (() => {
  // 省略(適当に作る)
})();

/**
 * @param {Object} [opts]
 * @param {string} [opts.root]
 * @param {string} [opts.spDir]
 */
const deviceRedirect = (opts = {}) => {
  const { root, spDir } = Object.assign({ root: '/', spDir: 'sp/' }, opts);
  const { pathname } = location;

  if(pathname.match(new RegExp(`^${ root }${ spDir }`))) {
    if(isMobile) return;
  } else {
    if(!isMobile) return;
  }

  const _before   = isMobile ? `^${ root }` : `^${ root }${ spDir }`;
  const _after    = isMobile ? (root + spDir) : root;
  const _pathname = pathname.replace(new RegExp(_before), _after);

  const { protocol, host, search, hash } = location;
  location.href = `${ protocol }//${ host }${ _pathname }${ search }${ hash }`;
};

使い方

// 例1
// PC    -> '/'
// スマホ -> '/sp/' 
deviceRedirect();

// 例2
// PC    -> '/sample/'
// スマホ -> '/sample/mobile/' 
deviceRedirect({ root: '/sample/', spDir: 'mobile/' });
1
1
0

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
1
1