页面失去焦点的时候如何触发事件

本人github

在JavaScript中,你可以使用blurfocus事件来检测页面是否失去或获得焦点。这些事件可以用于windowdocument对象。

使用blur事件

当页面失去焦点时,会触发blur事件。你可以这样添加一个事件监听器:

window.addEventListener('blur', function() {
    
    
  console.log('Page is out of focus');
  // 在这里保存localStorage或执行其他操作
});

使用focus事件

与之相反,当页面获得焦点时,会触发focus事件:

window.addEventListener('focus', function() {
    
    
  console.log('Page is in focus');
  // 在这里加载localStorage或执行其他操作
});

综合示例

下面是一个综合示例,展示了如何在页面失去和获得焦点时执行操作:

// 当页面失去焦点
window.addEventListener('blur', function() {
    
    
  console.log('Page is out of focus');
  // 在这里保存localStorage
  chrome.runtime.sendMessage({
    
    
    type: 'SAVE_LOCALSTORAGE',
    data: {
    
    ...localStorage}  // 当前页面的localStorage数据
  }, (response) => {
    
    
    console.log(response.status);  // 应输出 "Data saved"
  });
});

// 当页面获得焦点
window.addEventListener('focus', function() {
    
    
  console.log('Page is in focus');
  // 在这里加载localStorage
  chrome.runtime.sendMessage({
    
    type: 'LOAD_LOCALSTORAGE'}, (response) => {
    
    
    // 加载数据到当前页面的localStorage
    Object.assign(localStorage, response.data);
  });
});

这样,每当页面失去或获得焦点时,都会触发相应的事件,从而允许你保存或加载localStorage数据。

这种方法应该与你正在使用的Vue3、TypeScript、Tailwind和Manifest V3等技术完全兼容。希望这能帮助你!

猜你喜欢

转载自blog.csdn.net/m0_57236802/article/details/132849814