Let's say I am working with the following web page:
<html>
<body>
<span id="click">click me</span>
<script>
var hello = function() {
alert('hello');
}
document.getElementById('click').addEventListener('click', function(e) {
hello();
});
</script>
</body>
</html>
and my Greasemonkey script is:
// ==UserScript==
// @name My Script
// @include http://example.com/hello.html
// @version 1
// @grant none
// ==/UserScript==
window.hello = function() {
alert('goodbye');
}
With the Greasemonkey script disabled, clicking the #click
element on the page displays the 'hello' alert. With the script enabled, clicking the element displays the 'goodbye' alert.
Simple enough. The hello
function from the web page is being replaced by the function in the Greasemonkey script.
Now let's say I want to use a Greasemonkey API. When I set the @grant
value to a valid value other than 'none' (e.g. // @grant GM_setClipboard
) [which causes Greasemonkey to run the script as a "content script", rather than in the page's scope like with 'none'], the Greasemonkey script fails to work.
window.hello
is no longer targeting the correct object on the page.
Replacing window.hello
with unsafeWindow.hello
looks like it would work, but instead, the following error is thrown in the JS console:
Error: Permission denied to access object
How can I rewrite the Greasemonkey script while having @grant GM_setClipboard
set to target and replace the original hello
function on the page?
System information:
- Windows 7 64-bit
- Firefox 32.0
- Greasemonkey 2.2