lisonge / vite-plugin-monkey

A vite plugin server and build your.user.js for userscript engine like Tampermonkey, Violentmonkey, Greasemonkey, ScriptCat
MIT License
1.24k stars 65 forks source link

[Bug] mountGmApi to unsafeWindow bug #112

Closed 2214962083 closed 7 months ago

2214962083 commented 8 months ago
image

I still can't get GM api from unsafeWindow when i open the mountGmApi. after debug i found the monkeyWindow is proxy and can not map GM key from proxy, code here

export const mountGmApiFn = (meta: ImportMeta) => {
  const key = `__monkeyWindow-` + new URL(meta.url).origin;
  // @ts-ignore
  const monkeyWindow: Window = document[key];
  if (!monkeyWindow) {
    console.log(`[vite-plugin-monkey] not found monkeyWindow`);
    return;
  }

  // @ts-ignore
  window.unsafeWindow = window;
  console.log(`[vite-plugin-monkey] mount unsafeWindow to unsafeWindow`);

  const mountedApiList: string[] = [];
  Object.entries(monkeyWindow)
    .filter(([k]) => k.startsWith('GM'))
    .forEach(([k, fn]) => {
      // @ts-ignore
      window[k] = fn;
      mountedApiList.push(k);
    });
  console.log(
    `[vite-plugin-monkey] mount ${mountedApiList.length} GM_api to unsafeWindow`,
  );
};

I think the code should be:


const GM_API_NAMES = [
    'GM',
    'GM_addElement',
    'GM_addStyle',
    'GM_addValueChangeListener',
    'GM_cookie',
    'GM_deleteValue',
    'GM_download',
    'GM_getResourceText',
    'GM_getResourceURL',
    'GM_getTab',
    'GM_getTabs',
    'GM_getValue',
    'GM_info',
    'GM_listValues',
    'GM_log',
    'GM_notification',
    'GM_openInTab',
    'GM_registerMenuCommand',
    'GM_removeValueChangeListener',
    'GM_saveTab',
    'GM_setClipboard',
    'GM_setValue',
    'GM_unregisterMenuCommand',
    'GM_xmlhttpRequest',
    'GM_webRequest',
    'unsafeWindow',
    'monkeyWindow',
  ]

export const mountGmApiFn = (meta: ImportMeta) => {
  const key = `__monkeyWindow-` + new URL(meta.url).origin;
  // @ts-ignore
  const monkeyWindow: Window = document[key];
  if (!monkeyWindow) {
    console.log(`[vite-plugin-monkey] not found monkeyWindow`);
    return;
  }

  // @ts-ignore
  window.unsafeWindow = window;
  console.log(`[vite-plugin-monkey] mount unsafeWindow to unsafeWindow`);

  const mountedApiList: string[] = [];
  GM_API_NAMES.forEach((k) => {
      // @ts-ignore
      window[k] = monkeyWindow[k]
      mountedApiList.push(k);
    });
  console.log(
    `[vite-plugin-monkey] mount ${mountedApiList.length} GM_api to unsafeWindow`,
  );
};
lisonge commented 8 months ago

image

I use violentmonkey, It is work with startsWith('GM')

What is your userscript manager ?

lisonge commented 7 months ago

No feedback for a long time, closed temporarily