aboutsummaryrefslogtreecommitdiff
path: root/src/background/tabs.js
blob: efecdc447c043a624b9fe2d70150175dc03de3b8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const closeTab = (id) => {
  return browser.tabs.remove(id);
};

const reopenTab = () => {
  return browser.sessions.getRecentlyClosed({
    maxResults: 1
  }).then((sessions) => {
    if (sessions.length === 0) {
      return;
    }
    let session = sessions[0];
    if (session.tab) {
      return browser.sessions.restore(session.tab.sessionId);
    } else {
      return browser.sessions.restore(session.window.sessionId);
    }
  });
};

const selectAt = (index) => {
  return browser.tabs.query({ currentWindow: true }, (tabs) => {
    if (tabs.length < 2) {
      return;
    }
    if (index < 0 || tabs.length <= index) {
      throw new RangeError(`tab ${index} does not exist`)
    }
    let id = tabs[index].id;
    return browser.tabs.update(id, { active: true })
  });
};

const selectByKeyword = (keyword) => {
  return browser.tabs.query({ currentWindow: true }).then((tabs) => {
    let matched = tabs.filter((t) => {
      return t.url.includes(keyword) || t.title.includes(keyword)
    })

    if (matched.length == 0) {
      throw new RangeError('No matching buffer for ' + keyword);
    } else if (matched.length >= 2) {
      throw new RangeError('More than one match for ' + keyword);
    }

    return browser.tabs.update(matched[0].id, { active: true });
  });
}

const selectPrevTab = (current, count) => {
  return browser.tabs.query({ currentWindow: true }, (tabs) => {
    if (tabs.length < 2) {
      return;
    }
    let select = (current - count) % tabs.length
    let id = tabs[select].id;
    return browser.tabs.update(id, { active: true })
  });
};

const selectNextTab = (current, count) => {
  return browser.tabs.query({ currentWindow: true }, (tabs) => {
    if (tabs.length < 2) {
      return;
    }
    let select = (current + count + tabs.length) % tabs.length
    let id = tabs[select].id;
    return browser.tabs.update(id, { active: true })
  });
};

const reload = (current, cache) => {
  return browser.tabs.reload(
    current.id,
    { bypassCache: cache }
  );
};

export { closeTab, reopenTab, selectAt, selectByKeyword, selectNextTab, selectPrevTab, reload };