引入jquery等第三方库

1
2
// @require      https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js
// @require      https://cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.min.js

引入外部Css样式文件

暂未发现油猴如何像引入js一样引入css文件。以下是纯javascript的实现:

1
2
3
4
5
6
7
8
9
function loadStyles(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(link);
}
loadStyles('https://cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.min.css');

定义样式

授权

1
// @grant        GM_addStyle

定义

1
GM_addStyle('.mycontainer{display:flex; justify-content:space-between;}

使用

1
2
var html = $('<div id="__dialog" title="相关搜索" class="mycontainer"></div>');
$('body').append(html);

请求外部资源

使用GM_xmlhttpRequest(details)来实现对外的http请求。

授权部分:
1
2
// @grant    GM_xmlhttpRequest
// @connect    recommend.eastmoney.com  #这是打算请求的网站域名
代码部分:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
GM_xmlhttpRequest({
        method: 'GET',
        url: 'http://quote.eastmoney.com/config/sidemenu.json',
        responseType: 'json', // arraybuffer, blob, json
        onload: res => {
            console.log(res);
            if (res.status == 200) {
                console.log(res.response);
            }
        },
        onerror: err => {
            console.error(err);
        }
    })
小技巧:绑定到unsafeWindow上
1
unsafeWindow.gmAjax = GM_xmlhttpRequest;  

绑定到window对象上,这样在网页window命名空间中可以直接使用gmAjax,相当于调用GM_xmlhttpRequest。