├── src ├── styles │ └── variables.scss ├── assets │ ├── logo.png │ └── logo.svg ├── views │ ├── About.vue │ └── Home.vue ├── store │ └── index.js ├── main.js ├── devtools │ ├── main.js │ ├── http-codes.json │ └── App.vue ├── plugins │ └── vuetify.js ├── router │ └── index.js ├── manifest.json ├── App.vue ├── components │ ├── vuetify-confirm │ │ ├── index.js │ │ └── Confirm.vue │ └── MonacoEditor.vue ├── background.js └── content-scripts │ └── content-script.js ├── .travis.yml ├── .gitignore ├── public ├── favicon.ico ├── preview1.png ├── preview2.png ├── icons │ ├── icon_38.png │ └── icon_128.png ├── _locales │ └── en │ │ └── messages.json ├── browser-extension.html └── index.html ├── babel.config.js ├── example ├── server.js └── index.html ├── .eslintrc.js ├── LICENSE ├── package.json ├── vue.config.js └── README.md /src/styles/variables.scss: -------------------------------------------------------------------------------- 1 | $font-size-root: 14px; 2 | $input-font-size: 14px; -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" 4 | - "8" 5 | sudo: true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | .history 4 | .vscode 5 | artifacts 6 | dist -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eshengsky/chrome-extension-mocker/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /public/preview1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eshengsky/chrome-extension-mocker/HEAD/public/preview1.png -------------------------------------------------------------------------------- /public/preview2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eshengsky/chrome-extension-mocker/HEAD/public/preview2.png -------------------------------------------------------------------------------- /src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eshengsky/chrome-extension-mocker/HEAD/src/assets/logo.png -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/cli-plugin-babel/preset', 4 | ], 5 | }; 6 | -------------------------------------------------------------------------------- /public/icons/icon_38.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eshengsky/chrome-extension-mocker/HEAD/public/icons/icon_38.png -------------------------------------------------------------------------------- /public/icons/icon_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eshengsky/chrome-extension-mocker/HEAD/public/icons/icon_128.png -------------------------------------------------------------------------------- /public/_locales/en/messages.json: -------------------------------------------------------------------------------- 1 | { 2 | "extName": { 3 | "message": "test", 4 | "description": "" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/views/About.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /src/views/Home.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 10 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import Vuex from 'vuex'; 3 | 4 | Vue.use(Vuex); 5 | 6 | export default new Vuex.Store({ 7 | state: { 8 | }, 9 | mutations: { 10 | }, 11 | actions: { 12 | }, 13 | modules: { 14 | }, 15 | }); 16 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import App from './App.vue'; 3 | import router from './router'; 4 | import store from './store'; 5 | 6 | Vue.config.productionTip = false; 7 | 8 | new Vue({ 9 | router, 10 | store, 11 | render: (h) => h(App) 12 | }).$mount('#app'); 13 | -------------------------------------------------------------------------------- /src/devtools/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import vuetify from '@/plugins/vuetify'; 3 | import App from './App.vue'; 4 | 5 | chrome.devtools.panels.create('Mocker', '', 'devtools.html'); 6 | 7 | /* eslint-disable no-new */ 8 | new Vue({ 9 | el: '#app', 10 | vuetify, 11 | render: (h) => h(App), 12 | }); 13 | -------------------------------------------------------------------------------- /public/browser-extension.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | <%= htmlWebpackPlugin.options.title %> 8 | 9 | 10 |
11 | 12 | 13 | -------------------------------------------------------------------------------- /example/server.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | 5 | http.createServer((req, res) => { 6 | if (req.url === '/example/index.html') { 7 | res.setHeader('content-type', 'text/html; charset=utf-8'); 8 | fs.createReadStream(path.resolve(__dirname, `..${req.url}`)).pipe(res); 9 | } else { 10 | res.end(); 11 | } 12 | }).listen(8369); 13 | console.log('Demo page url: http://localhost:8369/example/index.html'); 14 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true, 5 | webextensions: true, 6 | }, 7 | extends: [ 8 | 'plugin:vue/essential', 9 | '@vue/airbnb', 10 | ], 11 | parserOptions: { 12 | parser: 'babel-eslint', 13 | }, 14 | rules: { 15 | 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 16 | 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 17 | 'linebreak-style': 'off' 18 | }, 19 | }; -------------------------------------------------------------------------------- /src/assets/logo.svg: -------------------------------------------------------------------------------- 1 | Artboard 46 2 | -------------------------------------------------------------------------------- /src/plugins/vuetify.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | // eslint-disable-next-line import/no-extraneous-dependencies 3 | import '@mdi/font/css/materialdesignicons.css'; 4 | import Vuetify from 'vuetify/lib/framework'; 5 | import VuetifyConfirm from '../components/vuetify-confirm'; 6 | 7 | const vuetify = new Vuetify({ 8 | icons: { 9 | iconfont: 'mdi', 10 | }, 11 | }); 12 | 13 | Vue.use(Vuetify); 14 | Vue.use(VuetifyConfirm, { 15 | vuetify, 16 | buttonTrueText: 'OK', 17 | buttonFalseText: 'CANCEL', 18 | buttonTrueColor: 'error', 19 | buttonTrueFlat: false, 20 | color: 'warning', 21 | width: 350, 22 | }); 23 | 24 | export default vuetify; 25 | -------------------------------------------------------------------------------- /src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import VueRouter from 'vue-router'; 3 | import Home from '../views/Home.vue'; 4 | 5 | Vue.use(VueRouter); 6 | 7 | const routes = [ 8 | { 9 | path: '/', 10 | name: 'Home', 11 | component: Home, 12 | }, 13 | { 14 | path: '/about', 15 | name: 'About', 16 | // route level code-splitting 17 | // this generates a separate chunk (about.[hash].js) for this route 18 | // which is lazy-loaded when the route is visited. 19 | component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'), 20 | }, 21 | ]; 22 | 23 | const router = new VueRouter({ 24 | routes, 25 | }); 26 | 27 | export default router; 28 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "chrome-extension-mocker", 4 | "homepage_url": "http://localhost:8080/", 5 | "description": "A mock tool based on Chrome extension, no need to change any code, support dynamic mock data.", 6 | "default_locale": "en", 7 | "permissions": [ 8 | "storage", 9 | "webRequest", 10 | "webRequestBlocking", 11 | "http://*/", 12 | "https://*/", 13 | "", 14 | "*://*/*" 15 | ], 16 | "icons": { 17 | "16": "icons/icon_38.png", 18 | "48": "icons/icon_38.png", 19 | "128": "icons/icon_128.png" 20 | }, 21 | "background": { 22 | "scripts": [ 23 | "js/background.js" 24 | ] 25 | }, 26 | "content_scripts": [ 27 | { 28 | "matches": ["*://*/*"], 29 | "js": ["js/content-script.js"], 30 | "run_at": "document_start" 31 | } 32 | ], 33 | "devtools_page": "devtools.html", 34 | "browser_action": { 35 | "default_title": "Mocker", 36 | "default_icon": { 37 | "19": "icons/icon_38.png", 38 | "38": "icons/icon_38.png" 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Sky.Sun 孙正华 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 45 | 46 | 56 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chrome-extension-mocker", 3 | "version": "2.0.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service build --mode development --watch", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "better-mock": "^0.3.2", 12 | "core-js": "^3.6.5", 13 | "monaco-editor": "^0.30.1", 14 | "vue": "^2.6.11", 15 | "vue-router": "^3.2.0", 16 | "vuetify": "^2.4.0", 17 | "vuex": "^3.4.0" 18 | }, 19 | "devDependencies": { 20 | "@mdi/font": "^6.5.95", 21 | "@vue/cli-plugin-babel": "~4.5.0", 22 | "@vue/cli-plugin-eslint": "~4.5.0", 23 | "@vue/cli-plugin-router": "~4.5.0", 24 | "@vue/cli-plugin-vuex": "~4.5.0", 25 | "@vue/cli-service": "~4.5.0", 26 | "@vue/eslint-config-airbnb": "^5.0.2", 27 | "babel-eslint": "^10.1.0", 28 | "deepmerge": "^4.2.2", 29 | "eslint": "^6.7.2", 30 | "eslint-plugin-import": "^2.20.2", 31 | "eslint-plugin-vue": "^6.2.2", 32 | "monaco-editor-webpack-plugin": "^6.0.0", 33 | "sass": "~1.32", 34 | "sass-loader": "^10", 35 | "vue-cli-plugin-browser-extension": "latest", 36 | "vue-cli-plugin-vuetify": "^2.4.3", 37 | "vue-template-compiler": "^2.6.11", 38 | "vuetify-loader": "^1.7.0" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/components/vuetify-confirm/index.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-param-reassign */ 2 | import Confirm from './Confirm.vue'; 3 | 4 | function Install(Vue, options = {}) { 5 | const property = options.property || '$confirm'; 6 | delete options.property; 7 | const { vuetify } = options; 8 | delete options.vuetify; 9 | if (!vuetify) { 10 | console.warn('Module vuetify-confirm needs vuetify instance. Use Vue.use(VuetifyConfirm, { vuetify })'); 11 | } 12 | const Ctor = Vue.extend({ vuetify, ...Confirm }); 13 | function createDialogCmp(opt) { 14 | const container = document.querySelector('[data-app=true]') || document.body; 15 | return new Promise((resolve) => { 16 | const cmp = new Ctor({ 17 | propsData: { ...Vue.prototype[property].options, ...opt }, 18 | destroyed: () => { 19 | container.removeChild(cmp.$el); 20 | resolve(cmp.value); 21 | }, 22 | }); 23 | container.appendChild(cmp.$mount().$el); 24 | }); 25 | } 26 | 27 | function show(message, opt = {}) { 28 | opt.message = message; 29 | return createDialogCmp(opt); 30 | } 31 | 32 | Vue.prototype[property] = show; 33 | Vue.prototype[property].options = options || {}; 34 | } 35 | 36 | if (typeof window !== 'undefined' && window.Vue) { 37 | window.Vue.use(Install); 38 | } 39 | 40 | export default Install; 41 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | <%= htmlWebpackPlugin.options.title %> 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 |
21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /vue.config.js: -------------------------------------------------------------------------------- 1 | const MonacoEditorPlugin = require('monaco-editor-webpack-plugin'); 2 | const path = require('path'); 3 | module.exports = { 4 | configureWebpack: { 5 | plugins: [ 6 | new MonacoEditorPlugin({ 7 | // https://github.com/Microsoft/monaco-editor-webpack-plugin#options 8 | // Include a subset of languages support 9 | // Some language extensions like typescript are so huge that may impact build performance 10 | // e.g. Build full languages support with webpack 4.0 takes over 80 seconds 11 | // Languages are loaded on demand at runtime 12 | languages: ['javascript', 'css', 'html', 'typescript', 'json'], 13 | }), 14 | ], 15 | }, 16 | chainWebpack: (config) => { 17 | config.optimization.delete('splitChunks'); 18 | config.module.rule('js') 19 | .exclude.add(path.resolve(__dirname, 'src/content-scripts/content-script.js')); 20 | }, 21 | pages: { 22 | devtools: { 23 | template: 'public/browser-extension.html', 24 | entry: './src/devtools/main.js', 25 | title: 'Devtools', 26 | }, 27 | }, 28 | 29 | pluginOptions: { 30 | browserExtension: { 31 | componentOptions: { 32 | background: { 33 | entry: 'src/background.js', 34 | }, 35 | contentScripts: { 36 | entries: { 37 | 'content-script': [ 38 | 'src/content-scripts/content-script.js', 39 | ], 40 | }, 41 | }, 42 | }, 43 | }, 44 | }, 45 | 46 | transpileDependencies: [ 47 | 'vuetify', 48 | ], 49 | }; 50 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Example 7 | 32 | 33 | 34 | 35 |
36 |
Chrome extension mocker examples
37 | 38 | 39 |
40 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /src/background.js: -------------------------------------------------------------------------------- 1 | import mockjs from 'better-mock'; 2 | 3 | const storageCache = { 4 | mockData: [], 5 | enabled: 'Y', 6 | }; 7 | 8 | chrome.storage.sync.get((['mockData']), (result) => { 9 | storageCache.mockData = result.mockData || []; 10 | }); 11 | 12 | chrome.storage.sync.get((['enabled']), (result) => { 13 | storageCache.enabled = result.enabled || 'Y'; 14 | }); 15 | 16 | chrome.storage.onChanged.addListener((changes) => { 17 | if (changes.mockData && changes.mockData.newValue) { 18 | storageCache.mockData = changes.mockData.newValue; 19 | } 20 | if (changes.enabled && changes.enabled.newValue) { 21 | storageCache.enabled = changes.enabled.newValue; 22 | } 23 | console.log('Update data:', storageCache); 24 | }); 25 | 26 | function getMockData(url, method) { 27 | if (storageCache.enabled !== 'Y') { 28 | return null; 29 | } 30 | return (storageCache.mockData || []).find((rule) => { 31 | if (!rule.active) { 32 | return false; 33 | } 34 | if (rule.reqMethod && rule.reqMethod.toLowerCase() !== method.toLowerCase()) { 35 | // 如果规则配置了method,而当前请求的method与规则不一致,则不匹配 36 | return false; 37 | } 38 | if (rule.reqType === 2) { 39 | // 正则匹配 40 | return new RegExp(rule.reqUrl, 'gi').test(url); 41 | } 42 | // 模糊匹配 43 | return url.indexOf(rule.reqUrl) >= 0; 44 | }); 45 | } 46 | 47 | chrome.webRequest.onBeforeRequest.addListener( 48 | (details) => { 49 | const { url } = details; 50 | const { method } = details; 51 | const mockData = getMockData(url, method); 52 | if (mockData) { 53 | let requestBody = ''; 54 | 55 | // 尝试将原始的请求体转为支持中文的字符串 56 | try { 57 | const uint8array = new Uint8Array(details.requestBody.raw[0].bytes); 58 | requestBody = new TextDecoder('utf-8').decode(uint8array); 59 | } catch (e) { 60 | console.error('Prase requestBody failed!', e); 61 | } 62 | 63 | let { responseText } = mockData; 64 | try { 65 | if (mockData.contentType.indexOf('application/json') >= 0) { 66 | responseText = JSON.stringify(mockjs.mock(JSON.parse(responseText))); 67 | } 68 | } catch (err) { 69 | console.error('Error when use mockjs:', err); 70 | } 71 | mockData.responseText = responseText; 72 | 73 | const data = { 74 | message: 'The request returned mock data. Please view it in Console!', 75 | mock: true, 76 | mockData, 77 | reqData: { 78 | url: details.url, 79 | method: details.method, 80 | body: requestBody, 81 | }, 82 | }; 83 | return { 84 | // 注意这里必须要 encodeURIComponent 一下,否则特殊字符会丢失 85 | redirectUrl: `data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(data))}`, 86 | }; 87 | } 88 | 89 | return { 90 | cancel: false, 91 | }; 92 | }, 93 | { urls: [''] }, 94 | ['blocking', 'requestBody', 'extraHeaders'], 95 | ); 96 | -------------------------------------------------------------------------------- /src/components/vuetify-confirm/Confirm.vue: -------------------------------------------------------------------------------- 1 | 40 | 41 | 135 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # chrome-extension-mocker 4 | 5 | A mock tool based on Chrome extension, no need to change any code, support dynamic mock data. 6 | 7 | If you want to use v1 version, switch to [axios-mocker](https://github.com/eshengsky/chrome-extension-mocker/tree/axios-mocker) branch. 8 | 9 | ## Why need mock requests 10 | * Instead of waiting for the dependent web service to develop and deploy, you just need to define the interface fields and the front back end can be developed in parallel. 11 | * Some web service may contaminate the data in the production environment, while the real request will not be sent by simulating the request and specifying the response you want. 12 | * Many times, the web service may return various types of responses, and developers and testers need to verify if it is working correctly under different returns, for example, when web service status code is 500, the page can be displayed as expected. Creating the data through normal operations can sometimes be particularly cumbersome or difficult, while using mock requests is convenient, and boundary testing can be done efficiently if you want to return what you want. 13 | * It is the base of TDD (test-driven development) and automated testing. 14 | 15 | ## Preview 16 | ![](https://github.com/eshengsky/chrome-extension-mocker/blob/master/public/preview1.png) 17 | ![](https://github.com/eshengsky/chrome-extension-mocker/blob/master/public/preview2.png) 18 | 19 | ## Download 20 | 21 | Download from [Chrome Web Store](https://chrome.google.com/webstore/detail/kfmkpfnmkjgcalngkpkjpjngjkfkjecl). 22 | 23 | Or, download and install as following: 24 | 25 | 1. Download the latest package in [Release](https://github.com/eshengsky/chrome-extension-mocker/releases/latest) page. 26 | 2. Open Chrome, enter `chrome://extensions/` in the address bar to enter the Chrome extension page, and check the `Developer mode`. 27 | 3. Drag the downloaded zip file to the page, and click on the `Add Extension` button. 28 | 29 | ## Usage 30 | 31 | In Chrome browser, press `Ctrl+Shift+I` or `⌘+⌥+I` to open dev tools, go to `Mocker` panel. 32 | 33 | Click the New button, and enter the mock data you want. 34 | In Match Request panel, set which requests need to match, and in Mock Response panel, set the simulate response you want to return. 35 | 36 | Note that if one request is matched, the original request will be redirected into a data uri, you can see details in Console panel. 37 | 38 | ## Development 39 | 40 | ```bash 41 | $ yarn serve 42 | ``` 43 | 44 | ## Package 45 | 46 | ```bash 47 | $ yarn build 48 | ``` 49 | 50 | ## Example 51 | 52 | ```bash 53 | $ cd example 54 | $ node server.js 55 | ``` 56 | 57 | Visit http://localhost:8369/example/index.html. 58 | 59 | ## Licence 60 | 61 | MIT License 62 | 63 | Copyright (c) 2021 Sky.Sun 孙正华 64 | 65 | Permission is hereby granted, free of charge, to any person obtaining a copy 66 | of this software and associated documentation files (the "Software"), to deal 67 | in the Software without restriction, including without limitation the rights 68 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 69 | copies of the Software, and to permit persons to whom the Software is 70 | furnished to do so, subject to the following conditions: 71 | 72 | The above copyright notice and this permission notice shall be included in all 73 | copies or substantial portions of the Software. 74 | 75 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 76 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 77 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 78 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 79 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 80 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 81 | SOFTWARE. 82 | -------------------------------------------------------------------------------- /src/components/MonacoEditor.vue: -------------------------------------------------------------------------------- 1 | 177 | -------------------------------------------------------------------------------- /src/devtools/http-codes.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "code": 202, 4 | "phrase": "Accepted", 5 | "constant": "ACCEPTED", 6 | "comment": { 7 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3", 8 | "description": "The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing." 9 | } 10 | }, 11 | { 12 | "code": 502, 13 | "phrase": "Bad Gateway", 14 | "constant": "BAD_GATEWAY", 15 | "comment": { 16 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3", 17 | "description": "This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response." 18 | } 19 | }, 20 | { 21 | "code": 400, 22 | "phrase": "Bad Request", 23 | "constant": "BAD_REQUEST", 24 | "comment": { 25 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1", 26 | "description": "This response means that server could not understand the request due to invalid syntax." 27 | } 28 | }, 29 | { 30 | "code": 409, 31 | "phrase": "Conflict", 32 | "constant": "CONFLICT", 33 | "comment": { 34 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8", 35 | "description": "This response is sent when a request conflicts with the current state of the server." 36 | } 37 | }, 38 | { 39 | "code": 100, 40 | "phrase": "Continue", 41 | "constant": "CONTINUE", 42 | "comment": { 43 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1", 44 | "description": "This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished." 45 | } 46 | }, 47 | { 48 | "code": 201, 49 | "phrase": "Created", 50 | "constant": "CREATED", 51 | "comment": { 52 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2", 53 | "description": "The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request." 54 | } 55 | }, 56 | { 57 | "code": 417, 58 | "phrase": "Expectation Failed", 59 | "constant": "EXPECTATION_FAILED", 60 | "comment": { 61 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14", 62 | "description": "This response code means the expectation indicated by the Expect request header field can't be met by the server." 63 | } 64 | }, 65 | { 66 | "code": 424, 67 | "phrase": "Failed Dependency", 68 | "constant": "FAILED_DEPENDENCY", 69 | "comment": { 70 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5", 71 | "description": "The request failed due to failure of a previous request." 72 | } 73 | }, 74 | { 75 | "code": 403, 76 | "phrase": "Forbidden", 77 | "constant": "FORBIDDEN", 78 | "comment": { 79 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3", 80 | "description": "The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server." 81 | } 82 | }, 83 | { 84 | "code": 504, 85 | "phrase": "Gateway Timeout", 86 | "constant": "GATEWAY_TIMEOUT", 87 | "comment": { 88 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5", 89 | "description": "This error response is given when the server is acting as a gateway and cannot get a response in time." 90 | } 91 | }, 92 | { 93 | "code": 410, 94 | "phrase": "Gone", 95 | "constant": "GONE", 96 | "comment": { 97 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9", 98 | "description": "This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for \"limited-time, promotional services\". APIs should not feel compelled to indicate resources that have been deleted with this status code." 99 | } 100 | }, 101 | { 102 | "code": 505, 103 | "phrase": "HTTP Version Not Supported", 104 | "constant": "HTTP_VERSION_NOT_SUPPORTED", 105 | "comment": { 106 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6", 107 | "description": "The HTTP version used in the request is not supported by the server." 108 | } 109 | }, 110 | { 111 | "code": 418, 112 | "phrase": "I'm a teapot", 113 | "constant": "IM_A_TEAPOT", 114 | "comment": { 115 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2", 116 | "description": "Any attempt to brew coffee with a teapot should result in the error code \"418 I'm a teapot\". The resulting entity body MAY be short and stout." 117 | } 118 | }, 119 | { 120 | "code": 419, 121 | "phrase": "Insufficient Space on Resource", 122 | "constant": "INSUFFICIENT_SPACE_ON_RESOURCE", 123 | "comment": { 124 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6", 125 | "description": "The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action." 126 | } 127 | }, 128 | { 129 | "code": 507, 130 | "phrase": "Insufficient Storage", 131 | "constant": "INSUFFICIENT_STORAGE", 132 | "comment": { 133 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6", 134 | "description": "The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process." 135 | } 136 | }, 137 | { 138 | "code": 500, 139 | "phrase": "Internal Server Error", 140 | "constant": "INTERNAL_SERVER_ERROR", 141 | "comment": { 142 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1", 143 | "description": "The server encountered an unexpected condition that prevented it from fulfilling the request." 144 | } 145 | }, 146 | { 147 | "code": 411, 148 | "phrase": "Length Required", 149 | "constant": "LENGTH_REQUIRED", 150 | "comment": { 151 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10", 152 | "description": "The server rejected the request because the Content-Length header field is not defined and the server requires it." 153 | } 154 | }, 155 | { 156 | "code": 423, 157 | "phrase": "Locked", 158 | "constant": "LOCKED", 159 | "comment": { 160 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4", 161 | "description": "The resource that is being accessed is locked." 162 | } 163 | }, 164 | { 165 | "code": 420, 166 | "phrase": "Method Failure", 167 | "constant": "METHOD_FAILURE", 168 | "isDeprecated": true, 169 | "comment": { 170 | "doc": "Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt", 171 | "description": "A deprecated response used by the Spring Framework when a method has failed." 172 | } 173 | }, 174 | { 175 | "code": 405, 176 | "phrase": "Method Not Allowed", 177 | "constant": "METHOD_NOT_ALLOWED", 178 | "comment": { 179 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5", 180 | "description": "The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code." 181 | } 182 | }, 183 | { 184 | "code": 301, 185 | "phrase": "Moved Permanently", 186 | "constant": "MOVED_PERMANENTLY", 187 | "comment": { 188 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2", 189 | "description": "This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response." 190 | } 191 | }, 192 | { 193 | "code": 302, 194 | "phrase": "Moved Temporarily", 195 | "constant": "MOVED_TEMPORARILY", 196 | "comment": { 197 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3", 198 | "description": "This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests." 199 | } 200 | }, 201 | { 202 | "code": 207, 203 | "phrase": "Multi-Status", 204 | "constant": "MULTI_STATUS", 205 | "comment": { 206 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2", 207 | "description": "A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate." 208 | } 209 | }, 210 | { 211 | "code": 300, 212 | "phrase": "Multiple Choices", 213 | "constant": "MULTIPLE_CHOICES", 214 | "comment": { 215 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1", 216 | "description": "The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses." 217 | } 218 | }, 219 | { 220 | "code": 511, 221 | "phrase": "Network Authentication Required", 222 | "constant": "NETWORK_AUTHENTICATION_REQUIRED", 223 | "comment": { 224 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6", 225 | "description": "The 511 status code indicates that the client needs to authenticate to gain network access." 226 | } 227 | }, 228 | { 229 | "code": 204, 230 | "phrase": "No Content", 231 | "constant": "NO_CONTENT", 232 | "comment": { 233 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5", 234 | "description": "There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones." 235 | } 236 | }, 237 | { 238 | "code": 203, 239 | "phrase": "Non Authoritative Information", 240 | "constant": "NON_AUTHORITATIVE_INFORMATION", 241 | "comment": { 242 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4", 243 | "description": "This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response." 244 | } 245 | }, 246 | { 247 | "code": 406, 248 | "phrase": "Not Acceptable", 249 | "constant": "NOT_ACCEPTABLE", 250 | "comment": { 251 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6", 252 | "description": "This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent." 253 | } 254 | }, 255 | { 256 | "code": 404, 257 | "phrase": "Not Found", 258 | "constant": "NOT_FOUND", 259 | "comment": { 260 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4", 261 | "description": "The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web." 262 | } 263 | }, 264 | { 265 | "code": 501, 266 | "phrase": "Not Implemented", 267 | "constant": "NOT_IMPLEMENTED", 268 | "comment": { 269 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2", 270 | "description": "The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD." 271 | } 272 | }, 273 | { 274 | "code": 304, 275 | "phrase": "Not Modified", 276 | "constant": "NOT_MODIFIED", 277 | "comment": { 278 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1", 279 | "description": "This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response." 280 | } 281 | }, 282 | { 283 | "code": 200, 284 | "phrase": "OK", 285 | "constant": "OK", 286 | "comment": { 287 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1", 288 | "description": "The request has succeeded. The meaning of a success varies depending on the HTTP method:\nGET: The resource has been fetched and is transmitted in the message body.\nHEAD: The entity headers are in the message body.\nPOST: The resource describing the result of the action is transmitted in the message body.\nTRACE: The message body contains the request message as received by the server" 289 | } 290 | }, 291 | { 292 | "code": 206, 293 | "phrase": "Partial Content", 294 | "constant": "PARTIAL_CONTENT", 295 | "comment": { 296 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1", 297 | "description": "This response code is used because of range header sent by the client to separate download into multiple streams." 298 | } 299 | }, 300 | { 301 | "code": 402, 302 | "phrase": "Payment Required", 303 | "constant": "PAYMENT_REQUIRED", 304 | "comment": { 305 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2", 306 | "description": "This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently." 307 | } 308 | }, 309 | { 310 | "code": 308, 311 | "phrase": "Permanent Redirect", 312 | "constant": "PERMANENT_REDIRECT", 313 | "comment": { 314 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3", 315 | "description": "This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request." 316 | } 317 | }, 318 | { 319 | "code": 412, 320 | "phrase": "Precondition Failed", 321 | "constant": "PRECONDITION_FAILED", 322 | "comment": { 323 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2", 324 | "description": "The client has indicated preconditions in its headers which the server does not meet." 325 | } 326 | }, 327 | { 328 | "code": 428, 329 | "phrase": "Precondition Required", 330 | "constant": "PRECONDITION_REQUIRED", 331 | "comment": { 332 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3", 333 | "description": "The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict." 334 | } 335 | }, 336 | { 337 | "code": 102, 338 | "phrase": "Processing", 339 | "constant": "PROCESSING", 340 | "comment": { 341 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1", 342 | "description": "This code indicates that the server has received and is processing the request, but no response is available yet." 343 | } 344 | }, 345 | { 346 | "code": 407, 347 | "phrase": "Proxy Authentication Required", 348 | "constant": "PROXY_AUTHENTICATION_REQUIRED", 349 | "comment": { 350 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2", 351 | "description": "This is similar to 401 but authentication is needed to be done by a proxy." 352 | } 353 | }, 354 | { 355 | "code": 431, 356 | "phrase": "Request Header Fields Too Large", 357 | "constant": "REQUEST_HEADER_FIELDS_TOO_LARGE", 358 | "comment": { 359 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5", 360 | "description": "The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields." 361 | } 362 | }, 363 | { 364 | "code": 408, 365 | "phrase": "Request Timeout", 366 | "constant": "REQUEST_TIMEOUT", 367 | "comment": { 368 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7", 369 | "description": "This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message." 370 | } 371 | }, 372 | { 373 | "code": 413, 374 | "phrase": "Request Entity Too Large", 375 | "constant": "REQUEST_TOO_LONG", 376 | "comment": { 377 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11", 378 | "description": "Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field." 379 | } 380 | }, 381 | { 382 | "code": 414, 383 | "phrase": "Request-URI Too Long", 384 | "constant": "REQUEST_URI_TOO_LONG", 385 | "comment": { 386 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12", 387 | "description": "The URI requested by the client is longer than the server is willing to interpret." 388 | } 389 | }, 390 | { 391 | "code": 416, 392 | "phrase": "Requested Range Not Satisfiable", 393 | "constant": "REQUESTED_RANGE_NOT_SATISFIABLE", 394 | "comment": { 395 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4", 396 | "description": "The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data." 397 | } 398 | }, 399 | { 400 | "code": 205, 401 | "phrase": "Reset Content", 402 | "constant": "RESET_CONTENT", 403 | "comment": { 404 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6", 405 | "description": "This response code is sent after accomplishing request to tell user agent reset document view which sent this request." 406 | } 407 | }, 408 | { 409 | "code": 303, 410 | "phrase": "See Other", 411 | "constant": "SEE_OTHER", 412 | "comment": { 413 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4", 414 | "description": "Server sent this response to directing client to get requested resource to another URI with an GET request." 415 | } 416 | }, 417 | { 418 | "code": 503, 419 | "phrase": "Service Unavailable", 420 | "constant": "SERVICE_UNAVAILABLE", 421 | "comment": { 422 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4", 423 | "description": "The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached." 424 | } 425 | }, 426 | { 427 | "code": 101, 428 | "phrase": "Switching Protocols", 429 | "constant": "SWITCHING_PROTOCOLS", 430 | "comment": { 431 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2", 432 | "description": "This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too." 433 | } 434 | }, 435 | { 436 | "code": 307, 437 | "phrase": "Temporary Redirect", 438 | "constant": "TEMPORARY_REDIRECT", 439 | "comment": { 440 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7", 441 | "description": "Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request." 442 | } 443 | }, 444 | { 445 | "code": 429, 446 | "phrase": "Too Many Requests", 447 | "constant": "TOO_MANY_REQUESTS", 448 | "comment": { 449 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4", 450 | "description": "The user has sent too many requests in a given amount of time (\"rate limiting\")." 451 | } 452 | }, 453 | { 454 | "code": 401, 455 | "phrase": "Unauthorized", 456 | "constant": "UNAUTHORIZED", 457 | "comment": { 458 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1", 459 | "description": "Although the HTTP standard specifies \"unauthorized\", semantically this response means \"unauthenticated\". That is, the client must authenticate itself to get the requested response." 460 | } 461 | }, 462 | { 463 | "code": 451, 464 | "phrase": "Unavailable For Legal Reasons", 465 | "constant": "UNAVAILABLE_FOR_LEGAL_REASONS", 466 | "comment": { 467 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7725", 468 | "description": "The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government." 469 | } 470 | }, 471 | { 472 | "code": 422, 473 | "phrase": "Unprocessable Entity", 474 | "constant": "UNPROCESSABLE_ENTITY", 475 | "comment": { 476 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3", 477 | "description": "The request was well-formed but was unable to be followed due to semantic errors." 478 | } 479 | }, 480 | { 481 | "code": 415, 482 | "phrase": "Unsupported Media Type", 483 | "constant": "UNSUPPORTED_MEDIA_TYPE", 484 | "comment": { 485 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13", 486 | "description": "The media format of the requested data is not supported by the server, so the server is rejecting the request." 487 | } 488 | }, 489 | { 490 | "code": 305, 491 | "phrase": "Use Proxy", 492 | "constant": "USE_PROXY", 493 | "isDeprecated": true, 494 | "comment": { 495 | "doc": "Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6", 496 | "description": "Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy." 497 | } 498 | }, 499 | { 500 | "code": 421, 501 | "phrase": "Misdirected Request", 502 | "constant": "MISDIRECTED_REQUEST", 503 | "isDeprecated": false, 504 | "comment": { 505 | "doc": "Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2", 506 | "description": "Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI." 507 | } 508 | } 509 | ] -------------------------------------------------------------------------------- /src/devtools/App.vue: -------------------------------------------------------------------------------- 1 | 332 | 333 | 684 | 904 | -------------------------------------------------------------------------------- /src/content-scripts/content-script.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | // import mockjs from 'mockjs'; 3 | (function () { 4 | // function mockjs() { 5 | // !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Mock=e():t.Mock=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var a=n[r]={exports:{},id:r,loaded:!1};return t[r].call(a.exports,a,a.exports,e),a.loaded=!0,a.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){var r,a=n(1),o=n(3),u=n(5),i=n(20),l=n(23),c=n(25);"undefined"!=typeof window&&(r=n(27));/*! 6 | // Mock - 模拟请求 & 模拟数据 7 | // https://github.com/nuysoft/Mock 8 | // 墨智 mozhi.gyy@taobao.com nuysoft@gmail.com 9 | // */ 10 | // var s={Handler:a,Random:u,Util:o,XHR:r,RE:i,toJSONSchema:l,valid:c,heredoc:o.heredoc,setup:function(t){return r.setup(t)},_mocked:{}};s.version="1.0.1-beta3",r&&(r.Mock=s),s.mock=function(t,e,n){return 1===arguments.length?a.gen(t):(2===arguments.length&&(n=e,e=void 0),r&&(window.XMLHttpRequest=r),s._mocked[t+(e||"")]={rurl:t,rtype:e,template:n},s)},t.exports=s},function(module,exports,__webpack_require__){var Constant=__webpack_require__(2),Util=__webpack_require__(3),Parser=__webpack_require__(4),Random=__webpack_require__(5),RE=__webpack_require__(20),Handler={extend:Util.extend};Handler.gen=function(t,e,n){e=void 0==e?"":e+"",n=n||{},n={path:n.path||[Constant.GUID],templatePath:n.templatePath||[Constant.GUID++],currentContext:n.currentContext,templateCurrentContext:n.templateCurrentContext||t,root:n.root||n.currentContext,templateRoot:n.templateRoot||n.templateCurrentContext||t};var r,a=Parser.parse(e),o=Util.type(t);return Handler[o]?(r=Handler[o]({type:o,template:t,name:e,parsedName:e?e.replace(Constant.RE_KEY,"$1"):e,rule:a,context:n}),n.root||(n.root=r),r):t},Handler.extend({array:function(t){var e,n,r=[];if(0===t.template.length)return r;if(t.rule.parameters)if(1===t.rule.min&&void 0===t.rule.max)t.context.path.push(t.name),t.context.templatePath.push(t.name),r=Random.pick(Handler.gen(t.template,void 0,{path:t.context.path,templatePath:t.context.templatePath,currentContext:r,templateCurrentContext:t.template,root:t.context.root||r,templateRoot:t.context.templateRoot||t.template})),t.context.path.pop(),t.context.templatePath.pop();else if(t.rule.parameters[2])t.template.__order_index=t.template.__order_index||0,t.context.path.push(t.name),t.context.templatePath.push(t.name),r=Handler.gen(t.template,void 0,{path:t.context.path,templatePath:t.context.templatePath,currentContext:r,templateCurrentContext:t.template,root:t.context.root||r,templateRoot:t.context.templateRoot||t.template})[t.template.__order_index%t.template.length],t.template.__order_index+=+t.rule.parameters[2],t.context.path.pop(),t.context.templatePath.pop();else for(e=0;e1)return this.getValueByKeyPath(key,options);if(templateContext&&"object"==typeof templateContext&&key in templateContext&&placeholder!==templateContext[key])return templateContext[key]=Handler.gen(templateContext[key],key,{currentContext:obj,templateCurrentContext:templateContext}),templateContext[key];if(!(key in Random||lkey in Random||okey in Random))return placeholder;for(var i=0;i1&&(a=e.context.path.slice(0),a.pop(),a=this.normalizePath(a.concat(r)));try{t=r[r.length-1];for(var o=e.context.root,u=e.context.templateRoot,i=1;i1/(t+e)*t?!n:n):Math.random()>=.5},bool:function(t,e,n){return this.boolean(t,e,n)},natural:function(t,e){return t="undefined"!=typeof t?parseInt(t,10):0,e="undefined"!=typeof e?parseInt(e,10):9007199254740992,Math.round(Math.random()*(e-t))+t},integer:function(t,e){return t="undefined"!=typeof t?parseInt(t,10):-9007199254740992,e="undefined"!=typeof e?parseInt(e,10):9007199254740992,Math.round(Math.random()*(e-t))+t},int:function(t,e){return this.integer(t,e)},float:function(t,e,n,r){n=void 0===n?0:n,n=Math.max(Math.min(n,17),0),r=void 0===r?17:r,r=Math.max(Math.min(r,17),0);for(var a=this.integer(t,e)+".",o=0,u=this.natural(n,r);o1&&r--,o=6*r<1?e+6*(n-e)*r:2*r<1?n:3*r<2?e+(n-e)*(2/3-r)*6:e,a[c]=255*o;return a},hsl2hsv:function(t){var e,n,r=t[0],a=t[1]/100,o=t[2]/100;return o*=2,a*=o<=1?o:2-o,n=(o+a)/2,e=2*a/(o+a),[r,100*e,100*n]},hsv2rgb:function(t){var e=t[0]/60,n=t[1]/100,r=t[2]/100,a=Math.floor(e)%6,o=e-Math.floor(e),u=255*r*(1-n),i=255*r*(1-n*o),l=255*r*(1-n*(1-o));switch(r*=255,a){case 0:return[r,l,u];case 1:return[i,r,u];case 2:return[u,r,l];case 3:return[u,i,r];case 4:return[l,u,r];case 5:return[r,u,i]}},hsv2hsl:function(t){var e,n,r=t[0],a=t[1]/100,o=t[2]/100;return n=(2-a)*o,e=a*o,e/=n<=1?n:2-n,n/=2,[r,100*e,100*n]},rgb2hex:function(t,e,n){return"#"+((256+t<<8|e)<<8|n).toString(16).slice(1)},hex2rgb:function(t){return t="0x"+t.slice(1).replace(t.length>4?t:/./g,"$&$&")|0,[t>>16,t>>8&255,255&t]}}},function(t,e){t.exports={navy:{value:"#000080",nicer:"#001F3F"},blue:{value:"#0000ff",nicer:"#0074D9"},aqua:{value:"#00ffff",nicer:"#7FDBFF"},teal:{value:"#008080",nicer:"#39CCCC"},olive:{value:"#008000",nicer:"#3D9970"},green:{value:"#008000",nicer:"#2ECC40"},lime:{value:"#00ff00",nicer:"#01FF70"},yellow:{value:"#ffff00",nicer:"#FFDC00"},orange:{value:"#ffa500",nicer:"#FF851B"},red:{value:"#ff0000",nicer:"#FF4136"},maroon:{value:"#800000",nicer:"#85144B"},fuchsia:{value:"#ff00ff",nicer:"#F012BE"},purple:{value:"#800080",nicer:"#B10DC9"},silver:{value:"#c0c0c0",nicer:"#DDDDDD"},gray:{value:"#808080",nicer:"#AAAAAA"},black:{value:"#000000",nicer:"#111111"},white:{value:"#FFFFFF",nicer:"#FFFFFF"}}},function(t,e,n){function r(t,e,n,r){return void 0===n?a.natural(t,e):void 0===r?n:a.natural(parseInt(n,10),parseInt(r,10))}var a=n(6),o=n(14);t.exports={paragraph:function(t,e){for(var n=r(3,7,t,e),a=[],o=0;o1&&(e=[].slice.call(arguments,0));var n=t.options,r=n.context.templatePath.join("."),a=t.cache[r]=t.cache[r]||{index:0,array:e};return a.array[a.index++%a.array.length]}}},function(t,e){t.exports={first:function(){var t=["James","John","Robert","Michael","William","David","Richard","Charles","Joseph","Thomas","Christopher","Daniel","Paul","Mark","Donald","George","Kenneth","Steven","Edward","Brian","Ronald","Anthony","Kevin","Jason","Matthew","Gary","Timothy","Jose","Larry","Jeffrey","Frank","Scott","Eric"].concat(["Mary","Patricia","Linda","Barbara","Elizabeth","Jennifer","Maria","Susan","Margaret","Dorothy","Lisa","Nancy","Karen","Betty","Helen","Sandra","Donna","Carol","Ruth","Sharon","Michelle","Laura","Sarah","Kimberly","Deborah","Jessica","Shirley","Cynthia","Angela","Melissa","Brenda","Amy","Anna"]);return this.pick(t)},last:function(){var t=["Smith","Johnson","Williams","Brown","Jones","Miller","Davis","Garcia","Rodriguez","Wilson","Martinez","Anderson","Taylor","Thomas","Hernandez","Moore","Martin","Jackson","Thompson","White","Lopez","Lee","Gonzalez","Harris","Clark","Lewis","Robinson","Walker","Perez","Hall","Young","Allen"];return this.pick(t)},name:function(t){return this.first()+" "+(t?this.first()+" ":"")+this.last()},cfirst:function(){var t="王 李 张 刘 陈 杨 赵 黄 周 吴 徐 孙 胡 朱 高 林 何 郭 马 罗 梁 宋 郑 谢 韩 唐 冯 于 董 萧 程 曹 袁 邓 许 傅 沈 曾 彭 吕 苏 卢 蒋 蔡 贾 丁 魏 薛 叶 阎 余 潘 杜 戴 夏 锺 汪 田 任 姜 范 方 石 姚 谭 廖 邹 熊 金 陆 郝 孔 白 崔 康 毛 邱 秦 江 史 顾 侯 邵 孟 龙 万 段 雷 钱 汤 尹 黎 易 常 武 乔 贺 赖 龚 文".split(" ");return this.pick(t)},clast:function(){var t="伟 芳 娜 秀英 敏 静 丽 强 磊 军 洋 勇 艳 杰 娟 涛 明 超 秀兰 霞 平 刚 桂英".split(" ");return this.pick(t)},cname:function(){return this.cfirst()+this.clast()}}},function(t,e){t.exports={url:function(t,e){return(t||this.protocol())+"://"+(e||this.domain())+"/"+this.word()},protocol:function(){return this.pick("http ftp gopher mailto mid cid news nntp prospero telnet rlogin tn3270 wais".split(" "))},domain:function(t){return this.word()+"."+(t||this.tld())},tld:function(){return this.pick("com net org edu gov int mil cn com.cn net.cn gov.cn org.cn 中国 中国互联.公司 中国互联.网络 tel biz cc tv info name hk mobi asia cd travel pro museum coop aero ad ae af ag ai al am an ao aq ar as at au aw az ba bb bd be bf bg bh bi bj bm bn bo br bs bt bv bw by bz ca cc cf cg ch ci ck cl cm cn co cq cr cu cv cx cy cz de dj dk dm do dz ec ee eg eh es et ev fi fj fk fm fo fr ga gb gd ge gf gh gi gl gm gn gp gr gt gu gw gy hk hm hn hr ht hu id ie il in io iq ir is it jm jo jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md mg mh ml mm mn mo mp mq mr ms mt mv mw mx my mz na nc ne nf ng ni nl no np nr nt nu nz om qa pa pe pf pg ph pk pl pm pn pr pt pw py re ro ru rw sa sb sc sd se sg sh si sj sk sl sm sn so sr st su sy sz tc td tf tg th tj tk tm tn to tp tr tt tv tw tz ua ug uk us uy va vc ve vg vn vu wf ws ye yu za zm zr zw".split(" "))},email:function(t){return this.character("lower")+"."+this.word()+"@"+(t||this.word()+"."+this.tld())},ip:function(){return this.natural(0,255)+"."+this.natural(0,255)+"."+this.natural(0,255)+"."+this.natural(0,255)}}},function(t,e,n){var r=n(18),a=["东北","华北","华东","华中","华南","西南","西北"];t.exports={region:function(){return this.pick(a)},province:function(){return this.pick(r).name},city:function(t){var e=this.pick(r),n=this.pick(e.children);return t?[e.name,n.name].join(" "):n.name},county:function(t){var e=this.pick(r),n=this.pick(e.children),a=this.pick(n.children)||{name:"-"};return t?[e.name,n.name,a.name].join(" "):a.name},zip:function(t){for(var e="",n=0;n<(t||6);n++)e+=this.natural(0,9);return e}}},function(t,e){function n(t){for(var e,n={},r=0;ra;a++)o=t.charAt(a),"\n"===o?(e.seenCR||e.line++,e.column=1,e.seenCR=!1):"\r"===o||"\u2028"===o||"\u2029"===o?(e.line++,e.column=1,e.seenCR=!0):(e.column++,e.seenCR=!1)}return tr!==e&&(tr>e&&(tr=0,er={line:1,column:1,seenCR:!1}),n(er,tr,e),tr=e),er}function b(t){nr>Zn||(Zn>nr&&(nr=Zn,rr=[]),rr.push(t))}function w(t){var e=0;for(t.sort();eZn?(r=t.charAt(Zn),Zn++):(r=null,0===ar&&b(Hn)),null!==r?(Qn=e,n=Sn(r),null===n?(Zn=e,e=n):e=n):(Zn=e,e=kt)):(Zn=e,e=kt),e}function ft(){var e,n,r;return e=Zn,92===t.charCodeAt(Zn)?(n=Dn,Zn++):(n=null,0===ar&&b(qn)),null!==n?(Fn.test(t.charAt(Zn))?(r=t.charAt(Zn),Zn++):(r=null,0===ar&&b(Ln)),null!==r?(Qn=e,n=On(r),null===n?(Zn=e,e=n):e=n):(Zn=e,e=kt)):(Zn=e,e=kt),e}function dt(){var e,n,r,a;if(e=Zn,t.substr(Zn,2)===In?(n=In,Zn+=2):(n=null,0===ar&&b(jn)),null!==n){if(r=[],Nn.test(t.charAt(Zn))?(a=t.charAt(Zn),Zn++):(a=null,0===ar&&b(zn)),null!==a)for(;null!==a;)r.push(a),Nn.test(t.charAt(Zn))?(a=t.charAt(Zn),Zn++):(a=null,0===ar&&b(zn));else r=kt;null!==r?(Qn=e,n=Un(r),null===n?(Zn=e,e=n):e=n):(Zn=e,e=kt)}else Zn=e,e=kt;return e}function mt(){var e,n,r,a;if(e=Zn,t.substr(Zn,2)===Bn?(n=Bn,Zn+=2):(n=null,0===ar&&b(Gn)),null!==n){if(r=[],Xn.test(t.charAt(Zn))?(a=t.charAt(Zn),Zn++):(a=null,0===ar&&b(Kn)),null!==a)for(;null!==a;)r.push(a),Xn.test(t.charAt(Zn))?(a=t.charAt(Zn),Zn++):(a=null,0===ar&&b(Kn));else r=kt;null!==r?(Qn=e,n=Wn(r),null===n?(Zn=e,e=n):e=n):(Zn=e,e=kt)}else Zn=e,e=kt;return e}function vt(){var e,n,r,a;if(e=Zn,t.substr(Zn,2)===Yn?(n=Yn,Zn+=2):(n=null,0===ar&&b($n)),null!==n){if(r=[],Xn.test(t.charAt(Zn))?(a=t.charAt(Zn),Zn++):(a=null,0===ar&&b(Kn)),null!==a)for(;null!==a;)r.push(a),Xn.test(t.charAt(Zn))?(a=t.charAt(Zn),Zn++):(a=null,0===ar&&b(Kn));else r=kt;null!==r?(Qn=e,n=Jn(r),null===n?(Zn=e,e=n):e=n):(Zn=e,e=kt)}else Zn=e,e=kt;return e}function gt(){var e,n;return e=Zn,t.substr(Zn,2)===In?(n=In,Zn+=2):(n=null,0===ar&&b(jn)),null!==n&&(Qn=e,n=Vn()),null===n?(Zn=e,e=n):e=n,e}function xt(){var e,n,r;return e=Zn,92===t.charCodeAt(Zn)?(n=Dn,Zn++):(n=null,0===ar&&b(qn)),null!==n?(t.length>Zn?(r=t.charAt(Zn),Zn++):(r=null,0===ar&&b(Hn)),null!==r?(Qn=e,n=Fe(r),null===n?(Zn=e,e=n):e=n):(Zn=e,e=kt)):(Zn=e,e=kt),e}var yt,bt=arguments.length>1?arguments[1]:{},wt={regexp:C},Ct=C,kt=null,Et="",Rt="|",At='"|"',_t=function(t,e){return e?new r(t,e[1]):t},Mt=function(t,e,n){return new a([t].concat(e).concat([n]))},Pt="^",Tt='"^"',Ht=function(){return new n("start")},St="$",Dt='"$"',qt=function(){return new n("end")},Ft=function(t,e){return new i(t,e)},Lt="Quantifier",Ot=function(t,e){return e&&(t.greedy=!1),t},It="{",jt='"{"',Nt=",",zt='","',Ut="}",Bt='"}"',Gt=function(t,e){return new l(t,e)},Xt=",}",Kt='",}"',Wt=function(t){return new l(t,1/0)},Yt=function(t){return new l(t,t)},$t="+",Jt='"+"',Vt=function(){return new l(1,1/0)},Zt="*",Qt='"*"',te=function(){return new l(0,1/0)},ee="?",ne='"?"',re=function(){return new l(0,1)},ae=/^[0-9]/,oe="[0-9]",ue=function(t){return+t.join("")},ie="(",le='"("',ce=")",se='")"',he=function(t){return t},pe=function(t){return new u(t)},fe="?:",de='"?:"',me=function(t){return new o("non-capture-group",t)},ve="?=",ge='"?="',xe=function(t){return new o("positive-lookahead",t)},ye="?!",be='"?!"',we=function(t){return new o("negative-lookahead",t)},Ce="CharacterSet",ke="[",Ee='"["',Re="]",Ae='"]"',_e=function(t,e){return new c(!!t,e)},Me="CharacterRange",Pe="-",Te='"-"',He=function(t,e){return new s(t,e)},Se="Character",De=/^[^\\\]]/,qe="[^\\\\\\]]",Fe=function(t){return new h(t)},Le=".",Oe='"."',Ie=function(){return new n("any-character")},je="Literal",Ne=/^[^|\\\/.[()?+*$\^]/,ze="[^|\\\\\\/.[()?+*$\\^]",Ue="\\b",Be='"\\\\b"',Ge=function(){return new n("backspace")},Xe=function(){return new n("word-boundary")},Ke="\\B",We='"\\\\B"',Ye=function(){return new n("non-word-boundary")},$e="\\d",Je='"\\\\d"',Ve=function(){return new n("digit")},Ze="\\D",Qe='"\\\\D"',tn=function(){return new n("non-digit")},en="\\f",nn='"\\\\f"',rn=function(){return new n("form-feed")},an="\\n",on='"\\\\n"',un=function(){return new n("line-feed")},ln="\\r",cn='"\\\\r"',sn=function(){return new n("carriage-return")},hn="\\s",pn='"\\\\s"',fn=function(){return new n("white-space")},dn="\\S",mn='"\\\\S"',vn=function(){return new n("non-white-space")},gn="\\t",xn='"\\\\t"',yn=function(){return new n("tab")},bn="\\v",wn='"\\\\v"',Cn=function(){return new n("vertical-tab"); 13 | // },kn="\\w",En='"\\\\w"',Rn=function(){return new n("word")},An="\\W",_n='"\\\\W"',Mn=function(){return new n("non-word")},Pn="\\c",Tn='"\\\\c"',Hn="any character",Sn=function(t){return new v(t)},Dn="\\",qn='"\\\\"',Fn=/^[1-9]/,Ln="[1-9]",On=function(t){return new m(t)},In="\\0",jn='"\\\\0"',Nn=/^[0-7]/,zn="[0-7]",Un=function(t){return new d(t.join(""))},Bn="\\x",Gn='"\\\\x"',Xn=/^[0-9a-fA-F]/,Kn="[0-9a-fA-F]",Wn=function(t){return new f(t.join(""))},Yn="\\u",$n='"\\\\u"',Jn=function(t){return new p(t.join(""))},Vn=function(){return new n("null-character")},Zn=0,Qn=0,tr=0,er={line:1,column:1,seenCR:!1},nr=0,rr=[],ar=0;if("startRule"in bt){if(!(bt.startRule in wt))throw new Error("Can't start parsing from rule \""+bt.startRule+'".');Ct=wt[bt.startRule]}if(n.offset=x,n.text=g,yt=Ct(),null!==yt&&Zn===t.length)return yt;throw w(rr),Qn=Math.max(Zn,nr),new e(rr,Qnr)return!0;var u={path:e,type:t,actual:n,expected:r,action:"is greater than",message:o};return u.message=l.message(u),a.push(u),!1},lessThan:function(t,e,n,r,a,o){if(n=r)return!0;var u={path:e,type:t,actual:n,expected:r,action:"is greater than or equal to",message:o};return u.message=l.message(u),a.push(u),!1},lessThanOrEqualTo:function(t,e,n,r,a,o){if(n<=r)return!0;var u={path:e,type:t,actual:n,expected:r,action:"is less than or equal to",message:o};return u.message=l.message(u),a.push(u),!1}};r.Diff=i,r.Assert=l,t.exports=r},function(t,e,n){t.exports=n(28)},function(t,e,n){function r(){this.custom={events:{},requestHeaders:{},responseHeaders:{}}}function a(){function t(){try{return new window._XMLHttpRequest}catch(t){}}function e(){try{return new window._ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}var n=function(){var t=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,e=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,n=location.href,r=e.exec(n.toLowerCase())||[];return t.test(r[1])}();return window.ActiveXObject?!n&&t()||e():t()}function o(t){function e(t,e){return"string"===i.type(t)?t===e:"regexp"===i.type(t)?t.test(e):void 0}for(var n in r.Mock._mocked){var a=r.Mock._mocked[n];if((!a.rurl||e(a.rurl,t.url))&&(!a.rtype||e(a.rtype,t.type.toLowerCase())))return a}}function u(t,e){return i.isFunction(t.template)?t.template(e):r.Mock.mock(t.template)}var i=n(3);window._XMLHttpRequest=window.XMLHttpRequest,window._ActiveXObject=window.ActiveXObject;try{new window.Event("custom")}catch(t){window.Event=function(t,e,n,r){var a=document.createEvent("CustomEvent");return a.initCustomEvent(t,e,n,r),a}}var l={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},c="readystatechange loadstart progress abort error load timeout loadend".split(" "),s="timeout withCredentials".split(" "),h="readyState responseURL status statusText responseType response responseText responseXML".split(" "),p={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",300:"Multiple Choice",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"};r._settings={timeout:"10-100"},r.setup=function(t){return i.extend(r._settings,t),r._settings},i.extend(r,l),i.extend(r.prototype,l),r.prototype.mock=!0,r.prototype.match=!1,i.extend(r.prototype,{open:function(t,e,n,u,l){function p(t){for(var e=0;e= 200 && mockData.status < 300) ? 'color: green; font-weight: bold;' : 'color: red; font-weight: bold;', mockData.statusText); 49 | console.groupEnd(); 50 | 51 | // Response Headers 52 | if (mockData.responseHeaders) { 53 | console.group('Response Headers'); 54 | const headers = mockData.responseHeaders.split(/\r?\n/); 55 | headers.forEach((header) => { 56 | if (header.indexOf(':') > 0) { 57 | const arr = header.split(':'); 58 | const key = arr[0].trim().toLowerCase(); 59 | const value = arr[1].trim(); 60 | console.log(`%c${key}:`, 'font-weight: bold;', value); 61 | } 62 | }); 63 | console.groupEnd(); 64 | } 65 | 66 | // Response 67 | console.group('Response'); 68 | let response = ''; 69 | if (mockData.contentType.indexOf('application/json') > -1) { 70 | try { 71 | response = JSON.parse(mockData.responseText); 72 | } catch (err) { 73 | console.error(err); 74 | } 75 | } 76 | console.log(response); 77 | console.groupEnd(); 78 | 79 | console.groupEnd(); 80 | }; 81 | 82 | // eslint-disable-next-line no-underscore-dangle 83 | const _MOCKER_XMLHttpRequest = XMLHttpRequest; 84 | window._MOCKER_XMLHttpRequest = XMLHttpRequest; 85 | 86 | // eslint-disable-next-line no-global-assign 87 | XMLHttpRequest = function () { 88 | const actual = new _MOCKER_XMLHttpRequest(); 89 | const self = this; 90 | 91 | this.onreadystatechange = null; 92 | 93 | const onreadystatechangeCb = function () { 94 | if (self.onreadystatechange) { 95 | return self.onreadystatechange(); 96 | } 97 | }; 98 | 99 | actual.onreadystatechange = function () { 100 | if (this.readyState === 4) { 101 | const data = getMock(this); 102 | if (data) { 103 | const { mockData } = data; 104 | self.status = mockData.status; 105 | self.statusText = mockData.statusText; 106 | 107 | let { responseText } = mockData; 108 | // window.postMessage({ 109 | // mocker: true, 110 | // responseText 111 | // }) 112 | // try { 113 | // if (mockData.contentType.indexOf('application/json') >= 0) { 114 | // responseText = JSON.stringify(mockjs.mock(JSON.parse(responseText))); 115 | // } 116 | // } catch (err) { 117 | // console.error('Error when use mockjs:', err); 118 | // } 119 | self.responseText = responseText; 120 | self.response = responseText; 121 | let responseHeaders = `Content-Type: ${mockData.contentType}`; 122 | if (mockData.responseHeaders) { 123 | responseHeaders += `\n${mockData.responseHeaders}`; 124 | } 125 | mockData.responseHeaders = responseHeaders; 126 | Object.defineProperty(self, 'getAllResponseHeaders', { 127 | value() { 128 | return responseHeaders; 129 | }, 130 | }); 131 | if (mockData.delay > 0) { 132 | setTimeout(() => { 133 | onreadystatechangeCb(); 134 | printMockToConsole(data); 135 | }, mockData.delay); 136 | } else { 137 | onreadystatechangeCb(); 138 | printMockToConsole(data); 139 | } 140 | } else { 141 | // 不走mock 142 | ['status', 'statusText', 'responseText', 'response'].forEach((item) => { 143 | Object.defineProperty(self, item, { 144 | get() { return actual[item]; }, 145 | }); 146 | }); 147 | Object.defineProperty(self, 'getAllResponseHeaders', { 148 | value() { 149 | return actual.getAllResponseHeaders.apply(actual, arguments); 150 | }, 151 | }); 152 | onreadystatechangeCb(); 153 | } 154 | } else { 155 | onreadystatechangeCb(); 156 | } 157 | }; 158 | 159 | // add all proxy getters 160 | ['readyState', 'responseXML', 'upload'].forEach((item) => { 161 | Object.defineProperty(self, item, { 162 | get() { return actual[item]; }, 163 | }); 164 | }); 165 | 166 | // add all proxy getters/setters 167 | ['responseType', 'ontimeout', 'timeout', 'withCredentials', 'onload', 'onerror', 'onprogress'].forEach((item) => { 168 | Object.defineProperty(self, item, { 169 | get() { return actual[item]; }, 170 | set(val) { actual[item] = val; }, 171 | }); 172 | }); 173 | 174 | // add all pure proxy pass-through methods 175 | ['addEventListener', 'open', 'send', 'abort', 176 | 'getResponseHeader', 'overrideMimeType', 'setRequestHeader'].forEach((item) => { 177 | Object.defineProperty(self, item, { 178 | value(...args) { return actual[item].apply(actual, args); }, 179 | }); 180 | }); 181 | }; 182 | } 183 | 184 | function inject(fn) { 185 | const script = document.createElement('script'); 186 | script.text = `(${fn.toString()})();`; 187 | document.documentElement.appendChild(script); 188 | } 189 | 190 | let enabled = 'Y'; 191 | chrome.storage.sync.get((['enabled']), (result) => { 192 | enabled = result.enabled || 'Y'; 193 | if (enabled === 'Y') { 194 | // inject(mockjs); 195 | inject(script); 196 | } 197 | }); 198 | chrome.storage.onChanged.addListener((changes) => { 199 | if (changes.enabled && changes.enabled.newValue) { 200 | window.location.reload(); 201 | } 202 | }); 203 | 204 | // window.addEventListener('message', (event) => { 205 | // if (event.data && event.data.mocker) { 206 | // let responseText = event.data.responseText; 207 | // console.log(555, responseText) 208 | // } 209 | // }, false); 210 | }()); 211 | --------------------------------------------------------------------------------