0xhiryuu
0xhiryuu

Reputation: 403

How to access DOM after extension installation in Safari

Is it possible, to access DOM after completing installation of the Safari extension? I'm interested in accessing into HTML of the page from which this extension is being installed.

Upvotes: 2

Views: 1903

Answers (1)

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

You can achieve this by injecting JS scripts. The injected scripts have access to the DOM of the webpages they are injected into. Injected scripts have the same access privileges as scripts executed from the webpage’s host.

You can find more information here.

Calling a Function from an Injected Script

  1. List item
  2. Create an extension folder using Extension Builder. Copy the
  3. listings into a text editor and save as Injected.js and Global.html.
  4. Drag Injected.js and Global.html into your extension folder. Click
  5. Extension Global Page in Extension Builder and choose Global.html.
  6. Click New Script in End Scripts and choose Injected.js. Set the
  7. Extension Website Access level to All. Click Install.

Code Injected.js

var initialVal=1;
var calculatedVal=0 ;

function doBigCalc(theData) {
    safari.self.tab.dispatchMessage("calcThis",theData);
}

function getAnswer(theMessageEvent) {
    if (theMessageEvent.name === "theAnswer") {
        calculatedVal=theMessageEvent.message;
        console.log(calculatedVal);
    }
}
safari.self.addEventListener("message", getAnswer, false);

doBigCalc(initialVal);

Code Global.html

<!DOCTYPE HTML>
<html>
<head>
<title>global HTML page</title>
<script type="text/javascript">

function bigCalc(startVal, event) {
    // imagine hundreds of lines of code here...
    var endVal = startVal + 2;
    // return to sender
    event.target.page.dispatchMessage("theAnswer", endVal);
}

function respondToMessage(theMessageEvent) {
    if(theMessageEvent.name === "calcThis") {
        var startVal=theMessageEvent.message;
        bigCalc(startVal, theMessageEvent);
    }
}

    safari.application.addEventListener("message",respondToMessage,false);
</script>
</head>
<body>
</body>
</html>

Upvotes: 4

Related Questions