【问题标题】:How do we call a function inside the Chrome content-script from "on-event" attribute我们如何从“on-event”属性调用 Chrome 内容脚本中的函数
【发布时间】:2020-01-07 06:15:15
【问题描述】:

我们如何从 on-event 属性(例如“onmouseover=”)调用 Chrome 插件内容脚本中的函数,该函数的元素要么由代码注入,存在于内容脚本本身,要么是 dom 中的原始元素?

【问题讨论】:

    标签: javascript dom google-chrome-extension


    【解决方案1】:

    内容脚本在一个孤立的世界中运行,因此它们无法访问页面函数或页面创建的 JavaScript 对象(如 window 中的全局变量)。反之亦然,这就是它被称为“孤立”的原因。

    有两种解决方案:

    调度一个 DOM 事件。

    const el = document.querySelector('div[onmouseover]');
    el.dispatchEvent(new MouseEvent('mouseover', {bubbles: true}));
    

    在页面上下文中运行代码。

    function runInPageContext(fn, ...params) {
      const script = document.createElement('script');
      script.textContent = 'document.currentScript.remove();' +
        `(${fn})(${JSON.stringify(params).slice(1, -1)})`;
      document.documentElement.appendChild(script);
    }
    

    用法:

    runInPageContext(selector => {
      const el = document.querySelector(selector);
      el.onmouseover(new MouseEvent('mouseover', {bubbles: true}));
      // if you're sure the function doesn't use the event, call it directly:
      // el.onmouseover();
    }, '*[onmouseover]');
    

    传递元素是不可能的,但这里有一个解决方法:

    // el is an element in DOM
    const index = [...document.getElementsByTagName(el.tagName)].indexOf(el);
    runInPageContext(index => {
      const el = [...document.getElementsByTagName(el.tagName)][index];
      el.onmouseover(new MouseEvent('mouseover', {bubbles: true}));
    }, index);
    

    在 ShadowDOM 中无法正常工作,但这是一项单独的任务。

    【讨论】:

      猜你喜欢
      • 2013-11-12
      • 1970-01-01
      • 2010-09-28
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多