问题
For most of my code in my userscript, I'm need to use unsafeWindow
for the websites my script executes on. I do this by using // @grant unsafeWindow
. However, some of my code cannot be executed with unsafeWindow
and needs to run in Tampermonkey's isolated sandbox. How would I be able to do this? Something like this could work:
function disableUnsafeWindow() {
// Disable UnsafeWindow
}
function enableUnsafeWindow() {
// Enable unsafeWindow
}
function withUnsafeWindow() {
enableUnsafeWindow()
// Run the code using unsafeWindow
}
function withoutUnsafeWindow() {
disableUnsafeWindow();
// Remove unsafeWindow access and execute the code without unsafeWindow
}
withUnsafeWindow()
withoutUnsafeWindow()
回答1:
Use the isolated sandbox with the privileged userscript functions by default. Then, for the code that requires use of the native page, you could insert the code into a <script>
tag, eg:
const fnToRunOnNativePage = () => {
console.log('fnToRunOnNativePage');
};
const script = document.body.appendChild(document.createElement('script'));
script.textContent = '(' + fnToRunOnNativePage.toString() + ')();';
// to use information inside the function that was retrieved elsewhere in the script,
// pass arguments above
script.remove();
来源:https://stackoverflow.com/questions/65545401/how-do-i-make-my-userscript-execute-code-in-isolated-sandbox-and-unsafewindow-to