In this article, we will learn about the error, “Permission denied to access property ‘target’“.
The ‘target’ element returns an element, for which the event, has been called. This error can occur, on any property, not only on the ‘target’ property. For example, the same error can occur for ‘document’ also. This error occurs, when, the passed object does not follow the web’s same origin policy. In Google chrome and firefox, this error occurs as a DOMException, and in Safari, it occurs as a security error.
The same origin policy, states that the files and resources can be shared among servers if they have the same protocol and host.
This error, mainly occurs due to the <iframe> tag, which is to pull data from a third party, this violates the same origin policy, as the same origin policy, allows restrictions over third-party usage, for security reasons.
For resolving this problem, one could either remove the <iframe> tag, used, or you can either add Access-Control-Allow-Origin.
Example 1: This example creates the same origin error, which indeed leads to the “permission denied to access property ‘target’”. Different browsers might give different errors, but ultimately the meaning is the same.
HTML
<!DOCTYPE html> < html lang = "en-US" > < head > < iframe id = "myframe" src = </ iframe > < script > onload = function () { console.log(frames[0].target); // Error: Permission denied to access property "target" }; </ script > </ head > < body ></ body > </ html > |
Output:
Note: The error can simply be solved by removing, the <iframe> tag, or adding Access-Control-Allow-Origin on your server side.
Example 2: In this example, we have simply removed the <iframe> tag. You might wonder if the error, is still occurring if you run the below code, but the error is occurring because, you have not declared any event, and the browser cannot read the properties of ‘target’, but actually the available error is removed. You could simply define an event to resolve it.
HTML
<!DOCTYPE html> < html lang = "en-US" > < head > < script > onload = function () { console.log(frames[0].target); }; </ script > </ head > < body ></ body > </ html > |
Output:
Note: Many times, it was seen that even if the iframe is not there in the code, the error still exists. You cannot do anything about it, as it might be a bug from the browser side which would be resolved soon if exists. For example, at the time of the release of the firefox 54.0 version, this error was occurring, but later it was fixed by the developers, and now no such problem exists, in the latest version of Firefox 105.0.3.