【转】Firefox Greasemonkey 学习笔记

admin 发表于 [Javascript] 分类,标签: 知识总结
0

Find all the elements with a title attribute

var allElements, thisElement;
allElements = document.evaluate(
    '//*[@title]',
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);
for (var i = 0; i < allElements.snapshotLength; i++) {
    thisElement = allElements.snapshotItem(i);
    switch (thisElement.nodeName.toUpperCase()) {
        case 'A':
            // this is a link, do something
            break;
        case 'IMG':
            // this is an image, do something else
            break;
        default:
            // do something with other kinds of HTML elements
    }
}

Inserting content before an element

var main, newElement;
main = document.getElementById('main');
if (main) {
    newElement = document.createElement('hr');
    main.parentNode.insertBefore(newElement, main);
}

Inserting content after an element

var navbar, newElement;
navbar = document.getElementById('navbar');
if (navbar) {
    newElement = document.createElement('hr');
    navbar.parentNode.insertBefore(newElement, navbar.nextSibling);
}

Removing an element

var adSidebar = document.getElementById('ads');
if (adSidebar) {
    adSidebar.parentNode.removeChild(adSidebar);
}

Replacing an element with new content

var theImage, altText;
theImage = document.getElementById('annoyingsmily');
if (theImage) {
    altText = document.createTextNode(theImage.alt);
    theImage.parentNode.replaceChild(altText, theImage);
}

Inserting complex HTML quickly

var logo = document.createElement("div");
logo.innerHTML = '<div style="margin: 0 auto 0 auto; ' +
    'border-bottom: 1px solid #000000; margin-bottom: 5px; ' +
    'font-size: small; background-color: #000000; ' +
    'color: #ffffff;"><p style="margin: 2px 0 1px 0;"> ' +
    'YOUR TEXT HERE ' +
    '</p></div>';
document.body.insertBefore(logo, document.body.firstChild);

Adding images without hitting a central server

var logo = document.createElement('img');
logo.src = 'data:image/gif;base64,R0lGODlhDQAOAJEAANno6wBmZgAAAAAAACH5BAAAAAAA'+
    'LAAAAAANAA4AQAIjjI8Iyw3GhACSQecutsFV3nzgNi7SVEbo06lZa66LRib2UQAAOw%3D%3D';
document.body.insertBefore(logo, document.body.firstChild);

Adding CSS styles

function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

addGlobalStyle('p { font-size: large ! important; }');

Get the actual style of an element

var p1elem, p2elem, p1style, p2style;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
p1style = getComputedStyle(p1elem, '');
p2style = getComputedStyle(p2elem, '');
alert(p1style.color); // will display "rgb(255, 0, 0)"
alert(p2style.color); // will display "rgb(0, 0, 255)"

Post-processing a page after it renders

var newBody =
'<html>' +
'<head>' +
'<title>My New Page</title>' +
'</head>' +
'<body>' +
'<p>This page is a complete replacement of the original.</p>' +
'</body>' +
'</html>';
window.addEventListener(
    'load',
    function() { document.body.innerHTML = newBody; },
    true);

Matching case-insensitive attribute values

var postforms = document.evaluate(
    "//form[translate(@method, 'POST ', 'post')='post']",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);

Rewriting links

var a = document.getElementById('article');
if (a.href.match(/\?/i)) {
    // link already contains other parameters, so append "&printer=1"
    a.href += '&printer=1';
} else {
    // link does not contain any parameters, so append "?printer=1"
    a.href += '?printer=1';
}

Intercepting user clicks

document.addEventListener('click', function(event) {
    // event.target is the element that was clicked

    // do whatever you want here

    // if you want to prevent the default click action
    // (such as following a link), use these two commands:
    event.stopPropagation();
    event.preventDefault();
}, true);

Overriding a built-in Javascript method

function newsubmit(event) {
    var target = event ? event.target : this;

    // do anything you like here
    alert('Submitting form to ' + target.action);

    // call real submit function
    this._submit();
}

// capture the onsubmit event on all forms
window.addEventListener('submit', newsubmit, true);

// If a script calls someForm.submit(), the onsubmit event does not fire,
// so we need to redefine the submit method of the HTMLFormElement class.
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = newsubmit;

Parsing XML

var xmlString = '<passwd>' +
'  <user id="101">' +
'    <login>mark</login>' +
'    <group id="100"/>' +
'    <displayname>Mark Pilgrim</displayname>' +
'    <homedir>/home/mark/</homedir>' +
'    <shell>/bin/bash</shell>' +
'  </user>' +
'</passwd>'
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "application/xml");

Parse XML from a remote source

GM_xmlhttpRequest({
    method: 'GET',
    url: 'http://greaseblog.blogspot.com/atom.xml',
    headers: {
        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
        'Accept': 'application/atom+xml,application/xml,text/xml',
    },
    onload: function(responseDetails) {
        var parser = new DOMParser();
        var dom = parser.parseFromString(responseDetails.responseText,
            "application/xml");
        var entries = dom.getElementsByTagName('entry');
        var title;
        for (var i = 0; i < entries.length; i++) {
            title = entries[i].getElementsByTagName('title')[0].textContent;
            alert(title);
        }
    }
});

生成并且操作 iframe 内容

<body><p>1231231231</p>
<script>
var css = 'position:; z-index:9999; top:0; left:0; border:0; margin:0; padding:0;overflow:hidden;'

var iframe = document.createElement('iframe');
iframe.setAttribute('style', css);

// The about:blank page becomes a blank(!) canvas to modify
iframe.src = 'about:blank';

document.body.appendChild(iframe);

// Make sure Firefox initializes the DOM before we try to use it.
iframe.addEventListener("load", function() {
    var doc = iframe.contentDocument;
    doc.body.style.background = 'red';
    doc.body.innerHTML = '<p>sdafawfwefwfw</p>.';
    iframe.style.width = doc.body.offsetWidth + "px";
    iframe.style.height = doc.body.offsetHeight + "px";
}, false);
</script>

说明:推荐使用 http://ecmanaut.googlecode.com/svn/trunk/lib/make-iframe.js js lib for firefox iframe

« 上一篇:PHP Filter 函数 Smarty3.0 使用指南:下一篇 »

发表我的评论