0

I write atypical property for DOM element in Chrome's Console:

document.getElementById('some_id').atypical_property = 'some text'

After, I try to read atypical_property in content_script.js:

alert(document.getElementById('some_id').atypical_property);

But this is unedfined! Ok. I try to read atypical_property in Chrome's Console and this is 'some text'! Run_at changing in manifest don't change result. I try use setTimeout, but many timer's iteration with delay 500 ms don't change result (typeof document.getElementById('some_id').atypical_property == "undefined")

The example with Chrome's console is example. In really script on website set atypical property and I hope to read it. Can I read this property?

Thanks in advance.

2 Answers2

1

Using elem.someProp = ... sets the property of the Node object (does not set an HTML attribute - e.g. if you check your HTML you'll not see any difference). Since content-scripts and the actual page share only the DOM (not the JS context, where the modified Node object "lives"), you need to modify the HTML for the changes to be visible to the content-script (although this limits the type of values to strings (or JSONifiable objects)).

document.getElementById('some_id').setAttribute('atypical_property', 'some text');

alert(document.getElementById('some_id').getAttribute('atypical_property'));

Alternatively, you could use the data- attributes (to the same effect):

document.getElementById('some_id').dataset.atypical_property = 'some text'

alert(document.getElementById('some_id').dataset.atypical_property);
gkalpak
  • 47,844
  • 8
  • 105
  • 118
1

Use creating script in embedding page and postMessage (this code in content_script.js):

window.addEventListener("message", function(event) {
    if (event.source != window)
       return;
    if (event.data.type && (event.data.type == "FROM_PAGE")) {
    //...
    }
}
function _script_(){
    function _tc_(sel){ 
        return typeof sel != "undefined" && sel !=null ? sel.t_content : "no";
    }

    window.postMessage({ 
        type: "FROM_PAGE",
        type_of_wp: _tc_(document.querySelector(".team-0 .withTip.firearms")),
        rank : _tc_(document.querySelector(".team-0 .withTip.sp.g1eb8.ic12453f2.d3710")),
        clothes: _tc_(document.querySelector(".team-0 .withTip.armor-plating")),
        house:_tc_(document.querySelector(".register.statistics img.withTip"))
    }, "*");
}
var n = document.createElement('script');
n.innerHTML = _script_.toString() + " _script_();";

document.body.appendChild(n);
  • 1
    1. Use `.textContent`, not `.innerHTML`. 2. Avoid leaking variables to pages (you're leaking `_script_`). By using `"(" + _script_ + ")();"` - see http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script – Rob W Jan 22 '14 at 09:23