在新标签页/窗口中传递数据或修改扩展名html [英] Pass data or modify extension html in a new tab/window

查看:96
本文介绍了在新标签页/窗口中传递数据或修改扩展名html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将DOM附加到从popup.js打开的自我chrome扩展文件中. 假设我有一个名为temp.html的Chrome扩展文件中存在的文件,在执行popup.js时的某个时刻,我使用chrome.tabs.create打开了此文件,然后我想将DOM附加到此html文件中.

I'm trying to append a DOM to a self chrome extension file opened from popup.js. Let's say I have a file that exists among chrome extension files called temp.html, At some point while executing popup.js, I open this file using chrome.tabs.create then I want to append a DOM to this html file.

反正我可以从popup.js这样做吗?

Is there anyway I could do so from popup.js ?

Extension files:

1-manifest.json
2-functions
    functions.js
    domToTables.js
3-libs
    jquery-3.3.1.min.js
    bootstrap-4.2.1-dist
4-myTables
    stylesheet.css
    *temp.html* \\this file
5-popup
    stylesheet.css
    index.html
    popup.js
6-background.js
7-content.js

推荐答案

尽管您可以使用chrome.extension.getViews直接访问在新标签页/窗口中打开的扩展程序页面的DOM(如果使用window.open,则更简单) ),但这是从UI原始的时代开始的方法,因此如果您打开的页面使用演示框架,它将无法正常工作.此外,从弹出窗口中使用时,您必须先在后台(chrome.tabs.create参数中的active:false)中打开选项卡,否则弹出窗口将自动关闭,因此无需其他代码会运行,但不幸的是仍然不可靠,因为另一个扩展程序可能会强制激活选项卡.

Although you can directly access DOM of your own extension's page opened in a new tab/window by using chrome.extension.getViews (or even simpler if window.open was used), but it's the approach from the times when UI was primitive so it won't work if your opened page uses a presentation framework. Moreover, when used from the popup you would have to open the tab in background first (active:false in the parameters of chrome.tabs.create), otherwise the popup will auto-close so no further code would run, which is unfortunately still unreliable because another extension may force-activate the tab.

可靠/正确的方法是将数据传递到另一个页面,并使其通过标准的<script src="other-page.js"></script>在该页面html中加载的脚本中处理数据.

The reliable/proper approach is to pass the data to the other page and let it handle the data inside its script that's loaded in that page html via the standard <script src="other-page.js"></script>.

如果您需要在第一个绘制框架之前的另一页内加载期间访问数据,请使用此选项,例如选择亮/暗主题.

Use if you need to access the data during loading inside the other page before the first painted frame e.g. to choose a light/dark theme.

缺点:大量数据可能会明显降低预算设备的速度,并且您必须对非字符串类型(例如对象或数组)进行JSON'修饰.

Disadvantage: big amounts of data could noticeably slow down a budget device and you'll have to JSON'ify the non-string types such as objects or arrays.

popup.js:

localStorage.sharedData = JSON.stringify({foo: 123, bar: [1, 2, 3], theme: 'dark'});
chrome.tabs.create({url: 'other-page.html'});

other-page.js:

other-page.js:

let sharedData;
try {
  sharedData = JSON.parse(localStorage.sharedData);
  if (sharedData.theme === 'dark') {
    document.documentElement.style = 'background: #000; color: #aaa;';
  }
} catch (e) {}
delete localStorage.sharedData;


2. URL参数+同步访问

如果您需要在第一个绘制框架之前的另一页内加载期间访问数据,请使用此选项,例如选择亮/暗主题.


2. URL parameters + synchronous access

Use if you need to access the data during loading inside the other page before the first painted frame e.g. to choose a light/dark theme.

缺点:地址栏中的网址很长,您必须对非字符串类型(例如对象或数组)进行JSON'修饰.

Disadvantage: a long url in the address bar and you'll have to JSON'ify the non-string types such as objects or arrays.

popup.js:

chrome.tabs.create({
  url: 'other-page.html?data=' + encodeURIComponent(JSON.stringify({foo: [1, 2, 3]})),
});

other-page.js:

other-page.js:

let sharedData;
try {
  sharedData = JSON.parse(new URLSearchParams(location.search).get('data'));
} catch (e) {}
// simplify the displayed URL in the address bar
history.replace({}, document.title, location.origin + location.pathname);


3.后台脚本的全局变量+同步访问

如果您需要在第一个绘制框架之前的另一页内加载期间访问数据,请使用此选项,例如选择亮/暗主题.


3. Background script's global variable + synchronous access

Use if you need to access the data during loading inside the other page before the first painted frame e.g. to choose a light/dark theme.

缺点1:需要背景页面.

Disadvantage 1: the need for a background page.

缺点2:需要使用JSON.parse(JSON.stringify(data))或适用于跨窗口上下文的自定义deepClone来深克隆对象,因为没有一种流行的deepClone实现可以做到这一点AFAIK:具体来说,它应该使用对象构造函数的目标window引用.

Disadvantage 2: the need to deep-clone the objects by using JSON.parse(JSON.stringify(data)) or a custom deepClone that works properly for cross-window contexts because none of the popular deepClone implementations do it AFAIK: specifically it should use the target window's reference of the object constructor.

manifest.json:

manifest.json:

"background": {
  "scripts": ["bg.js"],
  "persistent": false
}

popup.js:

// ensure the non-persistent background page is loaded
chrome.runtime.getBackgroundPage(bg => {
  // using JSON'ification to avoid dead cross-window references.
  bg.sharedData = JSON.stringify({foo: 123, bar: [1, 2, 3], theme: 'dark'});
  chrome.tabs.create({url: 'other-page.html'});
});

other-page.js:

other-page.js:

// if this tab was reloaded the background page may be unloaded and the variable is lost
// but we were saving a copy in HTML5 sessionStorage!
let sharedData = sessionStorage.sharedData;
if (!sharedData) {
  const bg = chrome.extension.getBackgroundPage();
  sharedData = bg && bg.sharedData;
  if (sharedData) {
    sessionStorage.sharedData = sharedData;
  }
}
// using JSON'ification to avoid dead cross-window references.
try {
  sharedData = JSON.parse(sharedData);
} catch (e) {}


4.两跳中的后台脚本中继消息传递

如果您需要在后台页面中执行一系列操作,则仅需打开其标签即可使用.例如,我们需要在第二步中传递数据.


4. Background script relay messaging in two hops

Use if you need to perform a sequence of actions in the background page of which opening the tab is just the first step. For example we need to pass the data in the second step.

需要背景页面,因为当在显示弹出窗口的同一窗口中打开活动选项卡时,弹出窗口将关闭并且其脚本将不再运行.可能有人认为使用active: false创建选项卡可以解决该问题,但是仅在用户决定安装另一个扩展选项卡打开行为之前,该扩展才可以解决.您可能会认为您可以打开一个新窗口,但又不能保证其他扩展程序不会将新窗口的选项卡重新附加到现有窗口中,从而关闭弹出窗口.

The background page is needed because the popup would be closed and its scripts won't run anymore when an active tab opens in the same window where the popup is displayed. One might think that creating a tab with active: false would solve the problem but only until a user decides to install another extension that overrides tab opening behavior. You would think you could open a new window but again there's no guarantee some other extension doesn't re-attach the new window's tab into the existing window thus closing your popup.

缺点1:在Chrome中,数据内部经过JSON修饰,因此使所有非标准类型(如WeakMap,TypedArray,Blob等)都受到干扰.在Firefox中,它们似乎正在使用结构化克隆,因此可以共享更多类型.

Disadvantage 1: in Chrome the data is JSON'ified internally so it nukes all the nonstandard types such as WeakMap, TypedArray, Blob, etc. In Firefox they seem to be using structured cloning so more types can be shared.

缺点2:我们两次发送相同的数据消息.

Disadvantage 2: we're sending the same data message twice.

注意:我正在使用 Mozilla的WebExtension polyfill .

manifest.json:

manifest.json:

"background": {
  "scripts": [
    "browser-polyfill.min.js",
    "bg.js"
  ],
  "persistent": false
}

popup.js:

chrome.runtime.sendMessage({
  action: 'openTab',
  url: '/other-page.html',
  data: {foo: 123, bar: [1, 2, 3], theme: 'dark'},
});

bg.js:

function onTabLoaded(tabId) {
  return new Promise(resolve => {
    browser.tabs.onUpdated.addListener(function onUpdated(id, change) {
      if (id === tabId && change.status === 'complete') {
        browser.tabs.onUpdated.removeListener(onUpdated);
        resolve();
      }
    });
  });
}

browser.runtime.onMessage.addListener(async (msg = {}, sender) => {
  if (msg.action === 'openTab') {
    const tab = await browser.tabs.create({url: msg.url});
    await onTabLoaded(tab.id);
    await browser.tabs.sendMessage(tab.id, {
      action: 'setData',
      data: msg.data,
    });
  }
});

other-page.html:

other-page.html:

<!doctype html>
<p id="text"></p>
<!-- scripts at the end of the page run when DOM is ready -->
<script src="other-page.js"></script>

other-page.js:

other-page.js:

chrome.runtime.onMessage.addListener((msg, sender) => {
  if (msg.action === 'setData') {
    console.log(msg.data);
    document.getElementById('text').textContent = JSON.stringify(msg.data, null, '  ');
    // you can use msg.data only inside this callback
    // and you can save it in a global variable to use in the code 
    // that's guaranteed to run at a later point in time
  }
});


5. chrome.storage.local

请参见此答案中的chrome.storage.local示例.


5. chrome.storage.local

See the example for chrome.storage.local in this answer.

这篇关于在新标签页/窗口中传递数据或修改扩展名html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆