Domanda

I'm creating a chrome extension that hides a jQuery element on the page when clicked.

I need to store a reference to this element in the chrome.storage API, so when the page is loaded at a later date I can have that element hidden again.

I know the DOM tree is rebuilt on page load, and I'm not sure if this will effect anything. The element could be anything on the page as well, so not necessarily having a class/id name.

What is the best way to go about storing the reference? I'm all out of ideas on how to do this (brand new to JavaScript).

Update

As suggested by Xan, I am now using xPath to store a reference to the element.

//Get the element

var elem = e.target || e.srcElement;
$(elem).click(function () {
            xPathOfElem = getElementXPath(elem); //Get xPath of element
            updateStorage(xPathOfElem);
            $(elem).hide("");
            return false;
        });

//Store it

function updateStorage(xPathOfElem) {
    chrome.storage.sync.set({"element":xPathOfElem} //set xPath to storage
        , function (data) {});
};

//Retrieve it on load later

function getStorage() {
     chrome.storage.sync.get(null, function (data) {
         $(getElementsByXPath(document, data.element)).hide(""); //get and hide element
     });
}

window.onload = function () {
     getStorage();
 };

As Xan mentioned, not a perfect approach if the page isn't static but it does what I need it to

È stato utile?

Soluzione

This is a very broad question and the reason is: in general, there is no way you can reliably pinpoint an element on a page, especially if it's dynamic.

There is no "single" solution that works for every page. However, assuming that you can devise a method of pinpointing an element, you should look into DOM XPath.

It's a rich way of describing how to find an element, much more general than class/id name. And it's just a string, so it can easily be stored. Once you have this description, you can find the element using document.evaluate.

The downside is, there is no such thing as "the XPath" of an element. You need to come up with your own method of constructing one for a given element, and like I said to do so automatically is nigh-impossible. You're certainly welcome to try an cover many common cases, but finding a universal solution is hopeless.

P.S. See this question for finding "an XPath" of an element. Again, would only work reliably in a static page.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top