Chrome 分机;通过可以与文档交互的弹出窗口制作一个对话框?

Chrome extension; making a dialog box via the popup that can interact with the document?

我做了一个小的 Chrome 扩展,可以为我自己自动化现场填充;目前刚刚在我的文档上运行 onkeydown event listener,它贯穿 content.js 文件。

此外,我还有一个弹出菜单(带有 popup.html 和 popup.js),其中有一些对我来说很方便的 link。

我正在尝试获取弹出菜单中的 link 之一创建一个小对话框(或弹出浏览器 window),它本身将包含一些 link (可能在 html 页面上),按下时,将填充打开它的文档中的某些字段;类似于事件侦听器的方式。

目前我有一个 link,在我的弹出窗口中,它只打开一个 'popup' 浏览器 window,但我找不到如何让它访问文档它被打开了。代码如下:

popup.js:

function newPopup(url) {
 popupWindow = window.open(url,'popUpWindow','height=300,width=400,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}

var link;

window.onload = function(){
 link = document.getElementById('templates');
 link.addEventListener('click', continueScript);
}
 
function continueScript(){
 newPopup('https://www.example-site.com/');
}

popup.html:

 <script src="popup.js"></script>
  <li><a class="templates" id="templates" href="#"><i class="fa fa-wpforms"></i>Templates</a></li>

现场人口只是价值编辑原则的工作,如下所示:

function fillForms(summary, description) {
                document.getElementById('example1').value = summary;
                document.getElementById('example2').value = description;
                document.getElementById('example2').focus();
                
              }

感谢您的帮助!

这个目标完全可以通过 chrome 扩展消息实现。下面的示例显示了如何通过单击对话框 window 中的 link 来更改文档的背景颜色。请确保您的 manifest.json 包含 activeTab 权限:

"permissions": [
  "activeTab"
]

首先,创建一个 dialog.html 文件和 link 你的 popup.js 中的函数:

function continueScript(){
    newPopup('dialog.html');
}

dialog.html:

<!doctype html>
<html>
  <head>
    <title>Dialog</title>
    <script src="dialog.js"></script>
  </head>
  <body>
    <a id="link" href="#">Change body color</a>
  </body>
</html>

dialog.js:

window.onload = function() {
  var link = document.getElementById('link');
  link.addEventListener('click', () => {
    // Get active tab.
    chrome.tabs.query({active: true}, (activeTabs) => {
      const tabId = activeTabs[0].id;
      const message = {
        backgroundColor: 'green'
      };
      const responseCallback = (responseMessage) => {
        // do something with the response if any ...
      };
      // Send a message to the content script of the active tab.
      chrome.tabs.sendMessage(tabId, message, {}, responseCallback);
    });
  });
};

然后在内容脚本中为消息添加监听器。

content.js:

window.onload = function() {
  // Listen for a message from dialog.js and send a response if needed.
  chrome.runtime.onMessage.addListener((message, sender, response) => {
    // Do stuff in your document.
    document.body.style.backgroundColor = message.backgroundColor;
  });
};

与传递和填写字段值的方式相同。

参考文献:

popup window in Chrome extension

https://developer.chrome.com/extensions/tabs#method-query

https://developer.chrome.com/apps/runtime#event-onMessage