Greasy Fork

Greasy Fork is available in English.

wsmud_api

使用于 Tampermonkey 的武神传说脚本的前置 API 库

当前为 2020-08-24 提交的版本,查看 最新版本

// ==UserScript==
// @name         wsmud_api
// @namespace    com.wsmud
// @version      0.0.1
// @description  使用于 Tampermonkey 的武神传说脚本的前置 API 库
// @author       sq
// @date         2020/08/24
// @modified     2020/08/24
// @match        http://*.wsmud.com/*
// @exclude      http://*.wsmud.com/news/*
// @exclude      http://*.wsmud.com/pay.html
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js
// @run-at       document-start
// @grant        unsafeWindow
// ==/UserScript==

(function() {

'use strict'

if (!WebSocket) return


class Api {
  constructor() {
    this.version = GM_info.script.version
    this._websocket = null
    this._onmessage = new Function()
    this.roles = this.getValue('roles')
    this.id = String()
    this.name = String('WSMUD')
    this.state = String()
  }
  set roles(value) {
    this._roles = Object(value)
    this.setValue('roles', this._roles)
  }
  get roles() {
    return this._roles
  }

  refreshTitle() {
    document.title = this.name + ' ' + this.state
  }
  green(value) {
    console.log(`%c${value}`, 'color:green')
  }
  orange(value) {
    console.log(`%c${value}`, 'color:orange')
  }
  setValue(key, value) {
    localStorage.setItem(key, JSON.stringify(value))
  }
  getValue(key) {
    return JSON.parse(localStorage.getItem(key))
  }

  onmessage(event) {
    this._onmessage(event)
  }
  onsend(command) {
    this._websocket.send(command)
    this.orange(command)
  }
}


const api = Vue.observable(new Api())
unsafeWindow.api = api


unsafeWindow.WebSocket = function (uri) {
  api._websocket = new WebSocket(uri)
}
unsafeWindow.WebSocket.prototype = {
  set onopen(fn) {
    api._websocket.onopen = fn
    api.green('Set: WebSocket.onopen')
  },
  set onclose(fn) {
    api._websocket.onclose = fn
    api.green('Set: WebSocket.onclose')
  },
  set onerror(fn) {
    api._websocket.onerror = fn
    api.green('Set: WebSocket.onerror')
  },
  set onmessage(fn) {
    api._onmessage = fn
    api._websocket.onmessage = api.onmessage.bind(api)
    api.green('Set: WebSocket.onmessage')
  },
  get readyState() {
    return api._websocket.readyState
  },
  send: function (command) {
    api.onsend(command)
  },
}


// To be continued...
})()