火狐插件油猴Greasemonkey系列二

用户脚本@require和@resource引入的脚本和资源在安装时下载一次,保存在用户脚本相同的位置。

bootstrap引入的css图片资源,是相对于css文件的,如果图片文件和css文件在相同的位置,则页面显示会有问题,只能修改css里面所有的图片资源不能包含路径,这个工作量很大,难度也很大。

如果将css文件和图片资源文件保存在服务器端,在用户脚本运行时动态加载到页面头文件,虽然每次都需要从服务器端下载CSS文件和资源文件,有些许网络资源消耗,但兼容性很好,是值得推荐的方法。

以下是加载bootstrap库的测试。

 1、准备web项目,路径结构如图:

 

2、page.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>游猴插件测试页面</title>
</head>
<body>
	<div id="container">
		<button onclick="alert('page button click event:' + $)">content button</button>
	</div>
	<div id="install"><a href="userscripts/test.user.js">用户脚本安装</a></div>
</body>
</html>

3、test.user.js

// ==UserScript==
// @name        test
// @namespace   http://yc.telecomjs.com/gm
// @description 油猴jQuery库测试
// @include     http://localhost:8080/gm/page.html
// @require		http://localhost:8080/gm/libs/jquery/jquery-1.12.1.min.js
// @require		http://localhost:8080/gm/libs/bootstrap-3.3.6/js/bootstrap.min.js
// @grant 		unsafeWindow
// @version     2.1
// ==/UserScript==

console.log('user script jquery:' + $.fn.jquery);

$('head').append('<link href="http://localhost:8080/gm/libs/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet">');

var button_str = '<button id="script_btn" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">' +
  'script button' + 
	'</button>';

var modal_str = 
'<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">' +
  '<div class="modal-dialog" role="document">' +
    '<div class="modal-content">' +
      '<div class="modal-header">' +
        '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
        '<h4 class="modal-title" id="myModalLabel">Modal title</h4>' +
      '</div>' +
      '<div class="modal-body">' +
        '测试' +
      '</div>' +
      '<div class="modal-footer">' +
        '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
        '<button type="button" class="btn btn-primary">Save changes</button>' +
      '</div>' +
    '</div>' +
  '</div>' +
'</div>';

$('#container').append(button_str);
$('#container').append(modal_str);

4、总结

以上代码经过部署测试,样式、事件均正常展示和触发,所以在引入重ajax库(jquery-ui、easyUI、bootstrap)时,由于包含图片、字体等相对路径文件,直接在用户脚本文件中引入是不方便的,通过ajax脚本方式从服务器取库文件是比较好的实践。

猜你喜欢

转载自nalan.iteye.com/blog/2281300