简体   繁体   English

在谷歌浏览器扩展中创建和访问全局变量

[英]Creating and accessing global variable in google chrome extension

All of the information I can find on this is pretty old.我能找到的所有关于这方面的信息都很老了。 Like the title says I am trying to make a global variable in one script and access it from another.就像标题说的那样,我试图在一个脚本中创建一个全局变量并从另一个脚本访问它。 The purpose of the extension is to search for a class named "page-title" and then return the innerHTML of that HTML element.扩展的目的是搜索名为“page-title”的 class,然后返回该 HTML 元素的 innerHTML。 Once I get the code working I will specify the URL I want the extension to run on so it's not constantly running.一旦我让代码工作,我将指定 URL 我希望扩展运行,因此它不会一直运行。

After a couple iterations trying to accomplish this in different ways I followed the method explained in this answer but my needs have different requirements and I am receiving the error "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist."经过几次迭代尝试以不同的方式完成此操作后,我遵循了此答案中解释的方法,但我的需求有不同的要求,我收到错误“未检查的 runtime.lastError:无法建立连接。接收端不存在。” tied to the popup.html.绑定到弹出窗口.html。 I tried the Unchecked runtime error solution found here but it's been awhile (~ 7 years) since I've dived into any coding and I'm not sure I implemented it correctly.我尝试了此处找到的未检查运行时错误解决方案,但自从我潜入任何编码以来已经有一段时间(约 7 年),我不确定我是否正确实现了它。 I've also tried to pass the value between JS documents is the HTML injection method, but without overriding security defaults in the manifest that doesn't really work.我还尝试在 JS 文档之间传递值是 HTML 注入方法,但没有覆盖清单中实际上不起作用的安全默认值。 It also seemed super bootstrappy and I wanted to pass the information in a more conventional way.它似乎也超级自举,我想以更传统的方式传递信息。 I tried creating a global variable by simply declaring the variable outside of a function/class/if statement and loading that.js file first, but that was unsuccessful as well.我尝试通过简单地在函数/类/if语句之外声明变量并首先加载 that.js 文件来创建全局变量,但这也没有成功。

Manifest显现

    "name": "P.P. to Sharepoint",
    "version": "1.0.0",
    "description": "Open P.P. client folder in sharepoint",
    "manifest_version": 3,
    "author": "Zach Morris",
    "action":{
        "default_popup": "popup.html",
        "default_title": "Open Sharepoint Folder"
    },
    "background": {
        "service_worker": "background.js"
    },
    "permissions": [
        "activeTab",
        "tabs",
        "scripting",
        "notifications"
    ],
    "content_scripts": [{
    "js": ["contentScript.js"],
    "matches": ["<all_urls>"]
    }]
}

popup.html My popup.html is super simple and really just has a button to press. popup.html我的 popup.html 超级简单,真的只有一个按钮可以按下。 I included all the.js files in the order I thought necessary我按照我认为必要的顺序包含了所有的 .js 文件

<script src="globalVariable.js"></script>
<script src="contentScript.js"></script>
<script src="popup.js"></script>
<script src="script.js"></script>
<script src="background.js"></script>

globalVariable.js This one is straight forward. globalVariable.js这个是直截了当的。 I need to pull the client's name out of the HTML of the page then use it in an API call when I click the button in popup.js This initializes the variable and uses it as place holder.我需要从页面的 HTML 中提取客户端的名称,然后在单击 popup.js 中的按钮时在 API 调用中使用它这会初始化变量并将其用作占位符。

var clientInfo = {
    name: 'test name'
};

ContentScript.js I only want to run this if importScripts is not undefined. ContentScript.js我只想在 importScripts 未定义时运行它。 So I threw it in the if statement.所以我把它扔在 if 语句中。 Then I make sure I pulled a client name from the page.然后我确保我从页面中提取了一个客户名称。 If not I throw an error message saying no client was found.如果不是,我会抛出一条错误消息,说没有找到客户端。

if( 'function' === typeof importScripts) {
  importScripts('globalVariable.js');

   addEventListener('message', onMessage);

   function onMessage(e) { 
    
        if(b[0]) {
            clientInfo.name = b[0].innerHTML;
            alert(clientInfo.name + ' was assigned!');
        } else {
            alert('There is no client on this screen ' + 'b[0] is ' + b[0] + " clientInfo = " + clientInfo.name);
        };
    }; 
} else {
    console.log("Your stupid code didn't work. ");
}

popup.js This one pulls up the globalVariable.js to use the clientInfo. popup.js这个拉起 globalVariable.js 来使用 clientInfo。 and makes a call to the button in background.js并调用 background.js 中的按钮

if( 'function' === typeof importScripts) {
   importScripts('globalVariable.js');
   addEventListener('message', onMessage);

   function onMessage(e) { 
      const text = clientInfo.name;
      const notify = document.getElementById( 'myButton' );

      notify.addEventListener( 'click', () => {
        chrome.runtime.sendMessage( '', {
          type: 'notification',
          message: text });
        
      } );
   }    
}

background.js Same thing here. background.js这里也一样。 I import the globalVariable script to use the global variable.我导入 globalVariable 脚本以使用全局变量。 The notification will eventually be replaced with the API call when the rest of the code is working properly.当代码的 rest 正常工作时,通知最终将被 API 调用替换。 I probably don't need to import the script here to access the variable because I can mass it with the event listener in popup.js, but I put it in here out of desperation.我可能不需要在此处导入脚本来访问该变量,因为我可以将它与 popup.js 中的事件侦听器一起批量处理,但我出于绝望将其放在这里。

if( 'function' === typeof importScripts) {
   importScripts('globalVariable.js');
   addEventListener('message', onMessage);

   function onMessage(e) { 
     // do some work here 
     chrome.runtime.onMessage.addListener( data => {
  if ( data.type === 'notification' ) {
          chrome.notifications.create(
              '',
              {
                  type: 'basic',
                  title: 'Notify!',
                  message: data.message || 'Notify!',
                  iconUrl: 'notify.png',
              }
          );
          console.log("sent notification");
  };

});
   }    
}

Try this method instead maybe?试试这个方法吧?

{
  var x = 2;
}

so:所以:

{
var clientInfo = {
    name: 'test name'
};
}

Not very good at this language, so I thought maybe you're missing the brackets?不太擅长这种语言,所以我想也许你错过了括号?

You can have the popup.js listen for a button click and content.js handle all the logic of finding the correct element.您可以让 popup.js 侦听按钮单击,而 content.js 处理查找正确元素的所有逻辑。

popup.js popup.js

document.querySelector('#btn').addEventListener('click', () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) =>
    chrome.tabs.sendMessage(tabs[0].id, { command: 'getClientName' })
  );
});

content.js内容.js

chrome.runtime.onMessage.addListener((msg, sender, response) => {
  if (msg.command === 'getClientName')
    findClientName(document.querySelectorAll('h3.page-title'));
});

Example of findClientName function: findClientName function 示例:

const findClientName = async (element) => {
  let clientName;
  if (element.length > 0) {
    element.length === 1
      ? (clientName = setClientName(element[0]))
      : handleMultipleElements(element);
  } else {
    handleNoClientNameFound();
  }
  clientName ? await makeAPIRequest(clientName) : null;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM