Home > Back-end >  Chrome Extension Background script: Change Mouse Cursor while loading
Chrome Extension Background script: Change Mouse Cursor while loading

Time:10-18

I'm new in creating chrome Extension. Currently I want to start a process which takes up to 5-10 seconds. During this period I want to change the Mouse Cursor to loading, that the user recognizes that something is doing.

The chrome extension is started via right-click on images. Afterwards the image is send to an api as base64 code.

During the whole process I Want that the mouse icon is changed to a loading circle, but I can't access the "document.body.style.cursor" object. "document" is not accessible in the background.js file.

Any help here? What I'm doing wrong? Thanks for any help / suggestions.

CodePudding user response:

This sample changes the cursor to wait when an image is selected and changes it back after 10 seconds.

Note:
If you have DevTools open, it won't come back until you move the cursor.

background.js

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "hoge",
    title: "Select image.",
    type: "normal",
    contexts: ["image"]
  });
});

const cursorToWait = () => {
  const style = document.createElement("style");
  style.id = "corsor_wait";
  style.innerHTML = "* {cursor: wait;}"
  document.head.insertBefore(style, null);
};

const restoreCursor = () => {
  document.getElementById("corsor_wait").remove();
};

chrome.contextMenus.onClicked.addListener(async () => {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  await chrome.scripting.executeScript({
    target: { tabId: tabs[0].id },
    function: cursorToWait
  });
  await new Promise(r => setTimeout(r, 10000));
  await chrome.scripting.executeScript({
    target: { tabId: tabs[0].id },
    function: restoreCursor
  });
});

manifest.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "contextMenus",
    "scripting"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

CodePudding user response:

In your Chrome extension Manifest V3, Use the content script and place your mouse cursor in the content.js file.

Manifest.json

"manifest_version": 3,
"content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["js/content.js"],
      "run_at": "document_end"
    }
  ],

content.js

document.body.style.cursor = 'wait';

And you can use message passing to know the status of the tab: https://developer.chrome.com/docs/extensions/mv3/messaging/

  • Related