簡體   English   中英

如何向 function 構造函數注入上下文?

[英]How to inject a context to the function constructor?

正如這里所解釋的,為了避免evil的方法,我使用了 function 構造函數。 沒有找到更好的方法來注入上下文:

  function evalContext(context: Record<string, unknown>) {
    const injectContext = Object.keys(context).reduce(
      (acc, key) => `${acc}${key}=context.${key};`,
      '',
    );
    return Function(`context`, `${injectContext}${script}`)(context);
  }

  const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = useEventCallback((event) => {
    if (event.code === 'KeyE' && event.metaKey) {
      evalContext({ a: 3, b: 4, log: console.log });
      event.preventDefault();
      event.stopPropagation();
    }
  });

在此處輸入圖像描述

盡管如此,它仍然有效(無需在鍵前加上this )。 主要問題是是否可以“隱藏”瀏覽器對象(窗口、文檔、位置……)。 從安全方面來看,function 構造函數中使用的腳本將只對帳戶所有者可見。 希望這是安全的。

作為一個附帶問題,嘗試使用一些代碼編輯器庫:monaco-editor、react-simple-code-editor、@uiw/react-textarea-code-editor、@patternfly/react-code-editor... Haven' t 設法運行其中的任何一個(在 next.js 上下文中打破了這個,打破了那個)。 請問你能推薦其中任何一個在 NJS 的最新版本中運行良好的嗎?

更新:

根據@kelly 的建議:

  function evalContext(context: Record<string, unknown>) {
    const injectContext = Object.keys(context).reduce(
      (acc, key) => `${acc}${key}=context.${key};`,
      '',
    );
    return Function(
      'context',
      'window',
      'document',
      'location',
      'localStorage',
      'navigation',
      'fetch',
      'frames',
      'history',
      `(function () {${injectContext}${script}}).call({})`,
    )(context);
  }

在此處輸入圖像描述

我想你可以通過添加參數來“覆蓋”全局名稱:

return Function(`context`, `window`, `globalThis`, `document`, ..., `${injectContext}${script}`)(context, undefined, undefined, undefined, ...);

與此示例類似:

function overridden(window) {
    window.open("site");
}

overridden(undefined); // error will occur

由於不提供參數與提供undefined基本相同,因此您可以完全省略undefined

return Function(`context`, `window`, `globalThis`, `document`, ..., `${injectContext}${script}`)(context);

請記住,全局命名空間中有很多東西。

Object.keys(window)會給你一個想法......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM