Reddit force local search

Force search in subreddit by default

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==

// @name        Reddit force local search

// @description Force search in subreddit by default

// @namespace   https://www.reddit.com/

// @match       https://www.reddit.com/*

// @grant       none

// @version     1.0

// @author      r/KaKi_87

// ==/UserScript==

const form = document.querySelector('#SearchDropdown form');

const getInput = () => document.querySelector('#header-search-bar');

const getSubreddit = () => {
  
  const path = window.location.href.split('/');
  
  return path[3] === 'r' ? path[4] : undefined;
  
};

const handler = event => {
  
  const
  
    query = getInput().value,
        
    subreddit = getSubreddit();
  
  if(!subreddit) return;
  
  event.stopPropagation();

  event.stopImmediatePropagation();

  event.preventDefault();

  window.location.href = `https://www.reddit.com/r/${subreddit}/search?q=${query}&restrict_sr=1`;
  
};

form.addEventListener('submit', handler, true);

const loop = () => {
  
  const subreddit = getSubreddit();
  
  const input = getInput();
  
  input.setAttribute('placeholder', subreddit ? `Search in r/${subreddit}` : 'Search');
  
  setTimeout(loop, 250);
  
};

loop();