unsafeWindow / Chrome, Tampermonkey Firefox.- ( ) JS jQuery, , .
- usercripts iframe,
@include, @exclude / @match.
, script, , , . :
(A) script (-), .
(B) JS frames, .
script , . Tampermonkey 1 ( Firefox Greasemonkey), jsBin.
console.log ("Script start...");
console.log ("calling functionOfInterest ()...");
unsafeWindow.functionOfInterest ();
if (window.top === window.self) {
console.log ("Userscript is in the MAIN page.");
withPages_jQuery (demoAccessToFramedJS);
}
else {
console.log ("Userscript is in the FRAMED page.");
console.log ("The frame ID is:", window.self.frameElement.id);
}
function demoAccessToFramedJS ($) {
$("body").prepend (
'<button id="gmMain">Run JS on main window</button>'
+ '<button id="gmFrame">Run JS on iframe</button>'
);
$("#gmMain, #gmFrame").click ( function () {
if (this.id === "gmMain") {
functionOfInterest ();
}
else {
frames[1].functionOfInterest ();
}
console.log (this.id + "was clicked.");
} );
}
function withPages_jQuery (NAMED_FunctionToRun) {
var funcText = NAMED_FunctionToRun.toString ();
var funcName = funcText.replace (/^function\s+(\w+)\s*\((.|\n|\r)+$/, "$1");
var script = document.createElement ("script");
script.textContent = funcText + "\n\n";
script.textContent += 'jQuery(document).ready(function() {'+funcName+'(jQuery);});';
document.body.appendChild (script);
};
console.log ("Script end");
, script , iframe. (Tampermonkey) :
Tampermonkey started
Script start...
calling functionOfInterest ()...
Userscript is in the MAIN page.
Script end
Tampermonkey started
Script start...
calling functionOfInterest ()...
Userscript is in the FRAMED page.
The frame ID is: iframe2
Script end
1 Chrome, unsafeWindow.